What is initState and super.initState In Flutter?

· 3 min read
What is initState and super.initState In Flutter
What is initState and super.initState In Flutter

Earlier, we have been through the entire flutter mobile application life cycle so in this article we will go through what is initState() and super.initState() in Flutter?

Let’s explore the same.

What is initState and super.initState In Flutter?

initState() is a method that is called once when the Stateful Widget is inserted in the widget tree. We generally override this method if we need to do some sort of initialization work like registering a listener because, unlike build(), this method is called once.

Uses of initState():

initState() is a method of class State and it is considered as an important lifecycle method in Flutter. initState() is called the only once and we use it for one-time initializations.

Example :

  • To initialize data that depends on the specific BuildContext.
  • To initialize data that need to execute before build()
  • Subscribe to Streams.

initState() is called once and only once. It must also call super.initState()

This @override method is the best time to:

  • Initialize data that relies on the specific BuildContext for the created instance of the widget.
  • Initialize properties that rely on these widgets ‘parent’ in the tree.
  • Subscribe to Streams, ChangeNotifiers, or any other object that could change the data on this widget.
    @override
    initState() {
      super.initState();
     // Add listeners to this class
    }

Example:

class InitExample extends StatefulWidget {
  const InitExample({Key? key}) : super(key: key);

  @override
  State createState() => _InitExampleState();
}

class _InitExampleState extends State {
  @override
  void initState() {
    super.initState();
    print("initState() called");
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("InitState Example"),
      ),
      body: const Center(
        child: Text("Welcome Flutter"),
      ),
    );
  }
}

Output:

initState() called

Conclusion:

Thanks for Reading !!!

In this article, We have been through what is initState() and super.initState() in Flutter?

Keep Learning !!! Keep Fluttering !!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Leave a comment

Your email address will not be published. Required fields are marked *