What is the difference between a StatelessWidget and a StatefulWidget in Flutter?




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?





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 Render Object Widgets, which describe concrete Render Objects).

·       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 Pr extends StatelessWidget {

  const Pr({ 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 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 call 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.

@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; }());
}






Comments

Popular posts from this blog

Auto slide image with indicator in flutter

Flutter Architecture | Flutter - Architecture Application

Automatic Scrolling Image in flutter