Tom Russell
Tom Russell

Reputation: 1063

Why does Flutter State object require a Widget?

The demo example has the following code, which is apparently typical of Flutter apps:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {...}
}

I'm OK, I guess, with MyHomePage overriding the StatefulWidget createState method. It's a little awkward but what the heck? And even depending on a State subclass. Fine.

But then having the State subclass turn around and depend on MyHomePage?! I'm having trouble wrapping my fairly abundant wits around that one.

So perhaps I'm unclear on what State<MyHomePage> is/does. With, say, Map<String, Object> the meaning is clear: Associate a string with an object. Can someone please elucidate? And if you could include something about the need for a state object to extend a widget, I would enjoy reading that.

Upvotes: 2

Views: 1099

Answers (2)

Rubens Melo
Rubens Melo

Reputation: 3305

In Flutter, everything is a widget and there are 2 types of widgets: Stateless and Statefull.

Stateless: A widget that does not require mutable state.

Statefull: A widget that has mutable state.

That is why all Statefull widget is dependent of a State<T>, because it manages changes (state) in the widget.

Upvotes: 2

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276911

This is to make widget properties access far easier. When you do

new MyStatefulWidget(foo: 42, bar: "string")

Then you most likely want to access foo/bar from your State.

Without such syntax you'd have to type custom State constructor and pass all StatefulWidget subclass properties to State subclass inside createState. Basically you'd have that:

class MyStatefulWidget extends StatefulWidget {
  final int foo;

  MyStatefulWidget({this.foo});

  @override
  MyStatefulWidgetState createState() => MyStatefulWidgetState(foo: foo);
}

class MyStatefulWidgetState extends State<MyStatefulWidget> {
  final int foo;

  MyStatefulWidgetState({this.foo});

  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }
}

Boring. You have to write all fields of StatefulWidget subclass twice.


With the current syntax; you don't have to do this. You can directly access all properties of the currently instantiated widget within State by using widget field.

class MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    print(widget.foo);
    return Container();
  }
}

Upvotes: 3

Related Questions