Home > Software design >  How should I implement the init method? In a stateful or stateless widget?
How should I implement the init method? In a stateful or stateless widget?

Time:02-22

What is the rule of thumb to use an initial method for a widget. Shall I use the:

  • A. classical stateful widget approach?

enter image description here

  • Or is it better to stick with the B. stateless widget approach?

enter image description here

Both seem to work from my testing. In terms of code reduction, it seems the B. approach is better, shorter, cleaner, and more readable. How about the performance aspect? Anything else that I could be missing?

CodePudding user response:

Initializing a controller should be a one-time operation; if you do it on a StatelessWidget's build method, it will be triggered every time this widget is rebuilt. If you do it on a StatefulWidget's initState, it will only be called once, when this object is inserted into the tree when the State is initialized.

  • Related