What is the relation between stateful and stateless widgets in Flutter?

点点圈 提交于 2019-11-27 09:56:30

问题


A stateful widget is defined as any widget which changes its state within its lifetime. But it is a very common practice for a StatelessWidget to have a StatefulWidget as one of its children. Doesn't StatelessWidget become stateful if it has StatefulWidget as one of its children?

I tried looking into the documentation as part of the code of StatelessWidget, but couldn't figure out how a StatelessWidget can have Statefulwidget as its children and still remain StatelessWidget.

What is the relation and difference between stateful and stateless widgets in Flutter?


回答1:


A StatelessWidget will never rebuild by itself (but can from external events). A StatefulWidget can. That is the golden rule.

BUT any kind of widget can be repainted any times.

Stateless only means that all of its properties are immutable and that the only way to change them is to create a new instance of that widget. It doesn't e.g. lock the widget tree.

But you shouldn't care about what's the type of your children. It doesn't have any impact on you.




回答2:


StatefulWidget vs StatelessWidget.

StatelessWidget:-- A widget that does not require mutable state.

  • A stateless widget is a widget that describes part of the user interface by building a constellation of other widgets that describe the user interface more concretely. The building process continues recursively until the description of the user interface is fully concrete (e.g., consists entirely of RenderObjectWidgets, which describe concrete RenderObjects).

  • The stateless widget is useful when the part of the user interface you are describing does not depend on anything other than the configuration information in the object itself and the BuildContext in which the widget is inflated. For compositions that can change dynamically, e.g. due to having an internal clock-driven state, or depending on some system state, consider using StatefulWidget.

class GreenFrog extends StatelessWidget {
  const GreenFrog({ Key key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFF2DBD3A));
  }
}

StatefulWidget:--A widget that has mutable state.

  • Stateful widgets are useful when the part of the user interface you are describing can change dynamically.

When a Flutter builds a StatefulWidget, it creates a State object. This object is where all the mutable state for that widget is held.

The concept of state is defined by two things:

1)The data used by the widget might change.

2) The data can't be read synchronously when the widget is built. (All state must be established by the time the build method is called).

StatefulWidget lifecycle

The lifecycle has the following simplified steps:

1-createState() :-- When Flutter is instructed to build a StatefulWidget, it immediately calls createState().

  • Creates the mutable state for this widget at a given location in the tree.

  • Subclasses should override this method to return a newly created instance of their associated State subclass:

@override
_MyState createState() => _MyState();

2-mounted == true :--All widgets have a bool this.mounted property. It turns true when the buildContext is assigned. It is an error to call setState when a widget is unmounted. Whether this State object is currently in a tree.

  • After creating a State object and before calling initState, the framework "mounts" the State object by associating it with a
    BuildContext. The State object remains mounted until the framework
    calls dispose(), after which time the framework will never ask the
    State object to build again.

  • It is an error to call setState unless mounted is true.

bool get mounted => _element != null;

3-initState():--This is the first method called when the widget is created (after the class constructor, of course.)

initState is called once and only once. It must called super.initState().

  • Initialize data that relies on the specific BuildContext for the created instance of the widget.

  • Initialize properties that rely on these widgets ‘parent’ in the tree.

  • Subscribe to Streams, ChangeNotifiers, or any other object that could change the data on this widget.

@override
initState() {
  super.initState();
  // Add listeners to this class
  cartItemStream.listen((data) {
    _updateWidget(data);
  });
}

4-didChangeDependencies():--Called when a dependency of this State object changes.

  • This method is also called immediately after initState. It is safe to call BuildContext.inheritFromWidgetOfExactType from this method.

  • Subclasses rarely override this method because the framework always calls build after dependency changes. Some subclasses do override this method because they need to do some expensive work (e.g., network fetches) when their dependencies change, and that work would be too expensive to do for every build.

@protected
@mustCallSuper
void didChangeDependencies() { }

5-build():--Describes the part of the user interface represented by the widget.

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).
  • After calling deactivate and then reinserting the State object into the tree at another location.
  • The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

  • Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor, the given BuildContext, and the internal state of this State object.

@override
  Widget build(BuildContext context, MyButtonState state) {
    ... () { print("color: $color"); } ...
  }

6-didUpdateWidget():--Called whenever the widget configuration changes.

  • If the parent widget rebuilds and request that this location in the tree update to display a new widget with the same runtime type and Widget.key, the framework will update the widget property of this State object to refer to the new widget and then call this method with the previous widget as an argument.

  • Override this method to respond when the widget changes (e.g., to start implicit animations).

  • The framework always calls build after calling didUpdateWidget, which means any calls to setState in didUpdateWidget are redundant.

@mustCallSuper
@protected
void didUpdateWidget(covariant T oldWidget) { }

7-setState():--Whenever you change the internal state of a State object, make the change in a function that you pass to setState:

  • 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 you just change the state directly without calling setState, the framework might not schedule a build and the user interface for this subtree might not be updated to reflect the new state.

setState(() { _myState = newValue });

8-deactivate():--Deactivate is called when State is removed from the tree, but it might be reinserted before the current frame change is finished. This method exists basically because State objects can be moved from one point in a tree to another.

  • The framework calls this method whenever it removes this State object from the tree. In some cases, the framework will reinsert the State object into another part of the tree (e.g., if the subtree containing this State object is grafted from one location in the tree to another). If that happens, the framework will ensure that it calls build to give the State object a chance to adapt to its new location in the tree. If the framework does reinsert this subtree, it will do so before the end of the animation frame in which the subtree was removed from the tree. For this reason, State objects can defer releasing most resources until the framework calls their dispose method.

This is rarely used.

@protected
@mustCallSuper
void deactivate() { }

9-dispose():--Called when this object is removed from the tree permanently.

  • The framework calls this method when this State object will never build again. After the framework calls dispose(), the State object is considered unmounted and the mounted property is false. It is an error to call setState at this point. This stage of the lifecycle is terminal: there is no way to remount a State object that has been disposed of.

  • Subclasses should override this method to release any resources retained by this object (e.g., stop any active animations).

@protected
@mustCallSuper
void dispose() {
  assert(_debugLifecycleState == _StateLifecycle.ready);
  assert(() { _debugLifecycleState = _StateLifecycle.defunct; return true; }());
}

For more info go here here, here




回答3:


From the documentation at flutter.io:

...The important thing to note here is at the core both Stateless and Stateful widgets behave the same. They rebuild every frame, the difference is the StatefulWidget has a State object which stores state data across frames and restores it.

If you are in doubt, then always remember this rule: If a widget changes (the user interacts with it, for example) it’s stateful. However, if a child is reacting to change, the containing parent can still be a Stateless widget if the parent doesn’t react to change.




回答4:


State is information that (1) can be read synchronously when the widget is built and (2) might change during the lifetime of the widget. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes, using State.setState.

StatefulWidget:

A stateful widget is a widget that describes part of the user interface by building a constellation of other widgets that describe the user interface more concretely. The building process continues recursively until the description of the user interface is fully concrete (e.g., consists entirely of RenderObjectWidgets, which describe concrete RenderObjects).

Stateful widget are useful when the part of the user interface you are describing can change dynamically, e.g. due to having an internal clock-driven state, or depending on some system state. For compositions that depend only on the configuration information in the object itself and the BuildContext in which the widget is inflated, consider using StatelessWidget.

StatefulWidget instances themselves are immutable and store their mutable state either in separate State objects that are created by the createState method, or in objects to which that State subscribes, for example Stream or ChangeNotifier objects, to which references are stored in final fields on the StatefulWidget itself.

StatelessWidget:

A stateless widget is a widget that describes part of the user interface by building a constellation of other widgets that describe the user interface more concretely. The building process continues recursively until the description of the user interface is fully concrete (e.g., consists entirely of RenderObjectWidgets, which describe concrete RenderObjects).

Stateless widget are useful when the part of the user interface you are describing does not depend on anything other than the configuration information in the object itself and the BuildContext in which the widget is inflated. For compositions that can change dynamically, e.g. due to having an internal clock-driven state, or depending on some system state, consider using StatefulWidget.




回答5:


As mention in flutter docs

What’s the point?

Some widgets are stateful, and some are stateless. If a widget changes—the user interacts with it, for example—it’s stateful. A widget’s state consists of values that can change, like a slider’s current value or whether a checkbox is checked. A widget’s state is stored in a State object, separating the widget’s state from its appearance. When the widget’s state changes, the state object calls setState(), telling the framework to redraw the widget.

A stateless widget has no internal state to manage. Icon, IconButton, and Text are examples of stateless widgets, which subclass StatelessWidget.

A stateful widget is dynamic. The user can interact with a stateful widget (by typing into a form, or moving a slider, for example), or it changes over time (perhaps a data feed causes the UI to update). Checkbox, Radio, Slider, InkWell, Form, and TextField are examples of stateful widgets, which subclass StatefulWidget.

https://flutter.io/tutorials/interactive/#stateful-stateless




回答6:


StackOverflow question on statefulness vs statelessness.

In Flutter, the difference is that stateless widgets can be defined by all the constructor arguments alone. If you create two stateless widgets using the same arguments, then they will be the same.

A stateful widget, however, is not necessarily the same as another built with the same constructor arguments. It might be in a different state.
Actually, a stateful widget is immutable (stateless) itself, but Flutter manages a separate state object and associates that with the widget, as explained in the StatefulWidget doc. This means that when Flutter rebuilds a stateful widget, it will check to see if it should reuse a previous state object and will, if desired, attach that state object to the widget.

The parent widget is stateless because it does not care about its child's state. The stateful child itself (or technically Flutter) will take care of its own state.
On a high level, I agree that this makes the parent widget stateful, because two parents might contain two childs with different states and thus be technically different themselves. But from the viewpoint of Flutter, it builds the parent widget without caring about the state and only when building the child will consider its statefullness.




回答7:


Stateless Widgets are static widgets. You just need to pass few properties before initializing Stateless Widgets. They do not depend on any data change or any behavior change. For Example. Text, Icon, RaisedButton are Stateless Widgets.

Stateful Widgets are dynamic widgets, they can be updated during runtime based on user action or data change. If a Widget can change its state during run time it will be stateful widget.

Edit 15/11/2018

Stateless Widgets can re-render if the input/external data changed (external data being data that is passed through the constructor). Because Stateless Widgets do not have a state, they will be rendered once and will not update themselves, but will only be updated when external data changes.

Whereas Stateful Widgets have an internal state and can re-render if the input data changes or if Widget's state changes.

Both stateless and stateful widgets have different lifecycle.



来源:https://stackoverflow.com/questions/47501710/what-is-the-relation-between-stateful-and-stateless-widgets-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!