Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

generics - Why are stateful widgets defined as two classes in flutter?

I'm new to flutter/dart, so while I try to make an app I also try to understand why things are a certain way. In the flutter docs there is example code of a stateful widget as shown:

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

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

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

Questions:

  1. Why are they defined with two classes as opposed to one? I'm guessing the State class can be used somewhere else so it was better to be split up.

  2. From what I understand the createState() function returns an object of type State, so having _YellowBirdState extends State makes sense, but why is YellowBird passed into the generic class of State? My guess it has something to do with Yellowbird extending the StatefulWidget class but not quite sure.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are multiple reasons :

  • Widgets are immutable. Since StatefulWidget extends Widget it therefore must be immutable too. Splitting the declaration into two classes allows both StatefulWidget to be immutable and State to be mutable.

  • Widgets are instantiated using the syntax new MyWidget(). If we merged both classes into one, new MyWidget() would reset all the properties of the state every time its parent update.

As for the explanation of class _MyStatefulState extends State<MyStateful>

That is because the State class can access to it's Stateful part using the this.widget field. The generic is here to make that field of type MyStateful instead of just StatefulWidget. As you may want to access MyStateful properties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...