introduce

The State life cycle is a question that is often asked. There are many related articles in digg’s article. This article records my learning process. Want to understand clearly, had better look seriously source code, big guy’s article is sometimes difficult to understand, but only truly understand the details to become their own thing.

preface

The original concept of State is to save State, but widgets themselves are immutable, which means widgets are lightweight and can be created and destroyed frequently. How does StateFulWidget save State?

In the previous article, we learned about the methods called by ELement, ComponentElement, StatelessElement, and update mechanism. If CanUpdate determines that ELement reuse is the same case, combining State will maintain State. We determine that State is associated with Element and look at the source code

StatefulElment

StatefulElement(StatefulWidget widget)
      : _state = widget.createState(),
        super(widget) {
    _state._element = this;
    _state._widget = widget;
  }
Copy the code

StatefulElement defines and holds the _state variable, which in turn holds the Element and widget

_firstBuild

@override
  void _firstBuild() {
    assert(_state._debugLifecycleState == _StateLifecycle.created);
    try {
      final dynamic debugCheckForReturnedFuture = _state.initState() as dynamic;
    } finally {
    }
  
    _state.didChangeDependencies();
    
    super._firstBuild();
  }
Copy the code

You can see that _firstBuild calls initState and didChangeDependencies, and then super._firstBuild(), which means ComponentElement, Super._firstbuild () finally calls rebuild()

performRebuild

  @override
  void performRebuild() {
    if (_didChangeDependencies) {
      _state.didChangeDependencies();
      _didChangeDependencies = false;
    }
    super.performRebuild();
  }
Copy the code

PerformRebuild method call super. PerformRebuild = > build (), updateChild, update the child, we see among _state. DidChangeDependencies (), Actually can be deduced from is inherited Shared component data changes, rebuild call _state. DidChangeDependencies (), later have the opportunity to can record the inherit

update

StatefulElement#update
  @override
  void update(StatefulWidget newWidget) {
    super.update(newWidget);
    final StatefulWidget oldWidget = _state._widget;
    _dirty = true;
    _state._widget = widget as StatefulWidget;
    try {
      final dynamic debugCheckForReturnedFuture = _state.didUpdateWidget(oldWidget) as dynamic;
    } finally {
    }
    rebuild();
  }
Copy the code
Element#update
@mustCallSuper
  void update(covariant Widget newWidget) {
    _widget = newWidget;
  }
Copy the code

The rebuild() recursion traverses the child with the same logic as StatelessElement, calling _state.didupDateWidget in the middle, so when didUpdateWidget is used, we can conclude: DidUpdateWidget is not called if element is not being reused.

conclusion

There is a specific map can refer to