I'm kinda confused, I have been looking into state management with flutter recently and I was wondering what happens if a custom stateful widget is placed in a stateless widget, let's say widgetA (parent) is a stateless widget and it has a child WidgetB which is a stateful widget and another child WidgetC which is a stateless widget.
Now my questions are:
if you have external links or resources that can help me understand please provide them
When you run the application, the setState() will fail to rebuild the widget. In this example, the initState() is called only once. This means the results of clicking + or – icons won't get displayed on the screen. However, this clicking will always execute the setState() and pass the new value to the widget tree.
If you call setState() on WidgetB it'll rebuild itself and it's descendants, no matter if they are Stateless or Stateful Widgets. Using the BLoC approach, most of the times it's optional to use Stateful Widgets and setState() to manage State.
Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.
If I say something wrong, someone please correct me.
Answering your questions in order:
If you call setState()
on WidgetB
it'll rebuild itself and it's descendants, no matter if they are Stateless
or Stateful
Widgets.
Using the BLoC approach, most of the times it's optional to use Stateful Widgets
and setState()
to manage State. In this approach you'll use events
from the UI, which will be converted into 'States' inside your BLoC. This States will be passed into a Stream. Your UI will rebuild itself using StreamBuilders
every time they listen to a new value on the Stream they're listening. This will trigger the StreamBuilder
to rebuilt itself and it's descendants.
If you're using BLoC
or Provider
+ Streams
, I would recommend avoiding setState()
and StatefulWidgets
, maybe with some exceptions like UI things, eg. animations.
BLoC is a design approach with goes nice with the Provider package
. The BLoC package
even uses Provider
internally.
P.S.: Whereas BLoC
is an Architecture Pattern to manage the Data and State of your application. Provider is 'just' a wrapper around Inherited Widgets
that facilitate exposure of Data throughout your Widget tree, not an Architecture Pattern.
Other example of architecture pattern solution to manage state that uses the provider
package is MobX
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With