简体   繁体   中英

Flutter StatefulWidget

Looking at the StatefulWidget usage, I am wondering about the design decision to have circular dependency like this:

class YellowBird extends StatefulWidget {
  const YellowBird({ Key key }) : super(key: key);

  @override
  _YellowBirdState createState() => _YellowBirdState();
}

class _YellowBirdState extends State<YellowBird> {
  @override
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFFFFE306));
  }
}

example is taken from Flutter StatefulWidget docs

Any thoughts?

这是构建有状态小部件的(一种)正确方法,并且与 flutter 文档完全一致。

This is not a circular dependency . You are defining a Stateful Widget class, and a corresponding State class. The Widget contains a State object (or rather a sub-class of it), using the principle of composition-over-inheritance .

From the Stateful widget documentation :

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.

This way Flutter framework can better manage the manipulation and change of this Widget's data. For example (from the link above):

[...] multiple State objects might be associated with the same StatefulWidget if that widget has been inserted into the tree in multiple places.

This principle of composition-over-inheritance is a core-concept of Flutter framework and most IDE's can create this boilerplate code for you automatically (eg typing stful on AndroidStudio suggests the StatefulWidgets class and its State related class) so you don't have to worry about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM