What is initState and super.initState in flutter?

Uses of initState()

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

Example :

  • To initialize data that depends on the specific BuildContext.

  • To initialize data that needs to executed before build().

  • Subscribe to Streams.

Credit to @Remi, initState() is a method which 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 initialisation work like registering a listener because, unlike build(), this method is called once.

And to unregister your listener (or doing some post work), you override dispose()method.

From here

A subclass of State can override initState to do work that needs to happen just once. For example, override initState to configure animations or to subscribe to platform services. Implementations of initState are required to start by calling super.initState

When a state object is no longer needed, the framework calls dispose() on the state object. Override the dispose function to do cleanup work. For example, override dispose to cancel timers or to unsubscribe from platform services. Implementations of dispose typically end by calling super.dispose