Flutter initState() vs build()?

It's in the comment within the build state of the link you provided.

 Widget build(BuildContext context) {

    // TODO: Instead of re-creating a list of Categories in every build(),

    // save this as a variable inside the State object and create

    // the list at initialization (in initState()).

    // This way, you also don't have to pass in the list of categories to

    // _buildCategoryWidgets()

     final categories = [];  

     ...

Creating Categories List in the Build State will lead to the list being created on every build. This is necessary since you only want it to be created once, so the best place to do this is in initState() since it will only be called once when the state object is created, Thereby eliminating the cost of re-creating the categories on each build.


According to flutter doc:

InitState


Called when this object is inserted into the tree.

The framework will call this method exactly once for each State object it creates.

Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget)


build


The framework calls this method in a number of different situations:

After calling initState.

After calling didUpdateWidget.

After receiving a call to setState.

After a dependency of this State object changes (e.g., an InheritedWidget referenced by the previous build changes).

Post a Comment

Previous Post Next Post

Subscribe Us


Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter

100% value, 0% spam. Unsubscribe anytime