flutterdartstatefulstatefulwidget

why use initState() in flutter, when we can just initailize a variable in the very first line of code


is there a difference in these 3 codes:

First: when i call my function inside onInit().

@override
  void onInit() {
    super.onInit();

    fetchProductsFromAPI();
  }

Second: when i call my function inside of build method, in stateless widget.

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    fetchProductsFromAPI();

    return GetMaterialApp(
      home: ShoppingPage(),
    );
  }
}

Third: when i call my function outside of build method, in stateless widget.

    class MyApp extends StatelessWidget {

  fetchProductsFromAPI();

  @override
  Widget build(BuildContext context) {

    return GetMaterialApp(
      home: ShoppingPage(),
    );
  }
}

Solution

  • Yes, there is a difference. You can read about flutter widget life cycle to have more details:

    In summary

    When you call your method outside of build method (your 3rd example).

    This is what is usually recommended when you can do it.

    See is there any difference between assigning value to the variable inside of initState or not in Flutter StatefulWidget?

    This will be run only once, when the class is created.

    Inside the initState (your 1st example)

    At this moment, your widget is being created. Some getters are already available, like the context. This method is called only once.

    Inside the build method (your 2nd example)

    This is usually the worst approach. Your method will be called for each and every build (you can consider 1 build = 1 frame) which can lead to poor performances. It is recommended to move those calls out of the build method when possible (and if it makes sense)

    See How to deal with unwanted widget build?