'Error in initializing AnimationController in flutter

I'm trying to make animated icon but I have an error in AnimationConroller _controller line, before I write any code for Icons. Here is the code:

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  @override
  void initState() {
    super.initState();
   
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            children: [],
          ),
        ));
  }
}


Solution 1:[1]

From around July 2020 Dart was becoming null safe. After that we can't keep variables uninitialized without explicitly specifying that they could be null or that they would be initialized later.

Solution 1 - Using late keyword

Replace AnimationController _controller with late AnimationController _controller

Late variables are used in two situations as per Dart documentation :

  • Declaring a non-nullable variable that’s initialized after its declaration.
  • Lazily initializing a variable.

Solution 2 - Using ? operator

? is called Operational spread operator in category of Null check operators

Replace AnimationController _controller with AnimationController? _controller;

? essentially means that a given variable can be null or have some other value as per its data type.

Example :

Color? favoriteColor means favoriteColor will either be null or have some appropriate value.

Solution 3 - using both late keyword and ? operator

Replace AnimationController _controller with late AnimationController? controller

For more information about Null Safety :

For more information about late keyword:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user18520267