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(),
);
}
}
CodePudding user response:
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.
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?
CodePudding user response:
First:
Put it on initState then the function fetchProductsFromAPI
will only call first time your widget create
Second:
I highly recommend you do not use this approach, because build method will be trigger many time when widget need to rebuild, if you put it there, your app will be fetchProductsFromAPI
at a lot of unexpected times.
Example when you need to call setState()
for some changes, you don't want to call fetch API
Third: This way will cause compile error, I don't think you can put it there like your code above