6. Flutter Tutorial for Beginners –initState(), setState() and dispose() in Flutter

0
2333

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.

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

Example:

@override
initState() {
  super.initState();
  _events = 'Predefined Data';
}

When you change the state of a stateful widget, use setState() to cause a rebuild of the widget and it’s descendants.

RaisedButton(
  onPressed: (){
    setState(() {
      data ="Change the data";
    });
  },

dispose() method use to release the memory allocated to variables when state object is removed.

For example, if you are using a stream in your application then you have to release memory allocated to streamController. Otherwise your app may get warning from play store and app store about memory leakage.

@override
void dispose() {
  // TODO: implement dispose
  super.dispose();
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here