0

I understand that StatefulWidget subclasses are intended to be immutable, and that we tend to store state in a State subclass. (Not talking advanced state management techniques here.)

What then, are the perils of storing our model/state in the StatefulWidget class instead of the State class? Since the State instance has a widget property referring to the StatefulWidget, why not store the state there?

For example:

class Foo extends StatefulWidget {

  int count = 0; // state

  State createState() => FooState();
}

class FooState extends State<Foo> {

  Widget build(BuildContext context) {
    return Column(children:[
      Text(widget.count.toString()),
      FloatingActionButton(
        onPressed: doIt
      )
    ]);
  }

  void doIt() {
    setState( () {
      widget.count += 1;
    });
  }

}

Would those concerns still apply when state is an object, passed down to the State instance?

For example:

class Foo extends StatefulWidget {

  final counter = Counter(0); // state

  State createState() => FooState(counter);
}

class FooState extends State<Foo> {

  final counter;

  FooState(this.counter);

  Widget build(BuildContext context) {
    return Column(children:[
      Text(counter.stringValue()),
      FloatingActionButton(
        onPressed: doIt
      )
    ]);
  }

  void doIt() {
    setState( () {
      counter.increment();
    });
  }

}
ybakos
  • 8,152
  • 7
  • 46
  • 74

1 Answers1

0

Immutability is used for performance reasons. If the widget needs to change, create a new instance set up accordingly. It's quicker to check if two instances are identical than if their state is the same.

Darish
  • 11,032
  • 5
  • 50
  • 70