5
class MyWidget extends StatefulWidget {
  // Here?

  @override
  State<MyWidget> createState() => MyWidgetState();
}

class MyWidgetState extends State<MyWidget> {
  // Or here?

  // ...
}

I want to understand where to store values associated with a stateful widget. On the widget or on the state?

  • It depends on the kind of variables (parameters vs internal state). Which one are you asking about? – Rémi Rousselet Jan 05 '20 at 18:03
  • This answer helped me to understand which fields correspond to what: https://stackoverflow.com/a/43874673/11573790 –  Jan 06 '20 at 15:08

1 Answers1

3

Please look at comments in the code to understand each use case:

class AnotherWidget extends StatefulWidget {
  final String fromParentVariable;

  AnotherWidget({
    this.fromParentVariable
  });

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

class _AnotherWidgetState extends State<AnotherWidget> {
  String localVariable;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        // You can access the variable coming from the parent by using the "widget." prefix.
        Text(widget.fromParentVariable),
        // You can access a local variable by simply calling normaly.
        Text(localVariable),
      ],
    );
  }
}

When calling the Widget you would do this:

AnotherWidget(fromParentVariable: 'my string',)
J. S.
  • 8,905
  • 2
  • 34
  • 44
  • Why not inside StatefulWidget class? –  Jan 05 '20 at 18:35
  • Because it's inside the State widget that you build your view and Widgets. inside the Stateful Widget you would declare the variables you expect to receive when MyWidget is being called by a parent Widget. I will update my response to help you understand. – J. S. Jan 05 '20 at 18:43
  • I've updated my response to better explain what you asked. – J. S. Jan 05 '20 at 18:48
  • If my response answered your question please don't forget to mark it as correct to help anyone else with the same question in the future. – J. S. Jan 05 '20 at 19:12
  • So I'm supposed to store all values that are not passed via widget's constructor on the state? –  Jan 05 '20 at 20:15
  • All the values that you want to use on that Widget, yes. You may be using multiple Widgets on the same view, or might even use a State Management solution like [ScopedModel](https://pub.dev/packages/scoped_model) that allows you to save you data on a single store that you share across your app. – J. S. Jan 05 '20 at 20:17