StatefulWidget, StatefulElement, and State relationships.

Demo code, the following use of demo-related objects refer to the objects in this demo

class Demo extends StatefulWidget { @override _DemoState createState() => _DemoState(); } class _DemoState extends State<Demo> { @override Widget build(BuildContext context) { return Scaffold( body: Text(' just a demo'),),); }}Copy the code

StatefulWidget

There are two main methods: createState and createElement, which createState and element, respectively

abstract class StatefulWidget extends Widget { const StatefulWidget({ Key key }) : super(key: key); Override StatefulElement createElement() => StatefulElement(this); // This method is overridden by subclasses, like _DemoState createState() => _DemoState(); @protected State createState(); } @override StatefulElement createElement() => StatefulElement(this); // Here this is the current StatefulWidget objectCopy the code

StatefulElement

The element corresponding to the StatefulWidget,

class StatefulElement extends ComponentElement { StatefulElement(StatefulWidget widget) CreateState () => _DemoState(); //_state is the created _DemoState object: _state = widget.createState(), Super (widget) {// bind _element and _widget to _DemoState // _element is the context in the _DemoState build method // _widget is the context in the _DemoState build method The widget in _DemoState, which inherits the StatefulWidget's Demo _state. _Element = this; _state._widget = widget; } //_state.build is the build method overridden in _DemoState. This is the context in build(BuildContext context). _state.build(this); State<StatefulWidget> get state => _state; State<StatefulWidget> _state; }Copy the code

Other relevant codes need to be added