0

Hopefully this is an easy one, but I'm a complete newbie to Flutter. I'm wondering how to reset a Widget's variable to its default, say when a button is pressed. I know I can hard code it (as I have in the example below), but surely there's a smarter way to simply have it reset to its default without explicitly setting it to the same value?

Thank you for any help!

class WidgetTest extends StatefulWidget {
  static const String id = 'widgettest_screen';
  @override
  _WidgetTestState createState() => _WidgetTestState();
}

class _WidgetTestState extends State<WidgetTest> {
  int _variable = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Text('$_variable'),
          IconButton(
            icon: Icon(
              Icons.add,
            ),
            onPressed: () {
              setState(() {
                _variable++;
              });
            },
          ),
          IconButton(
            icon: Icon(
              Icons.refresh,
            ),
            onPressed: () {
              setState(() {
                _variable = 0;
              });
            },
          )
        ],
      ),
    );
  }
}
Drew Moe
  • 29
  • 6
  • Once a widget is built it doesn't really know it's "original" state until a complete rebuild of it's state occurs (i.e the application being closed). So short answer, there really isn't a way to complete what you are asking with out doing what you are already doing.. – Apealed Nov 03 '21 at 00:53
  • What's wrong with resetting it to 0 in the `setState` method? Or you could declare a `const _default = 10;` and then set `_variable = _default;`. A lot of extra work to create a `StatefulWidget` for a simple use case. – Roslan Amir Nov 03 '21 at 06:56
  • There’s nothing horrible with being explicit about which value it resets to. I just assumed there was a simple bit of code to go back to its original value without resetting the entire widget. – Drew Moe Nov 04 '21 at 16:23

2 Answers2

1

When a StatefulWidget is rebuilt with a new Key, a new State is constructed.

An example implementation can be found in this answer to a similar question.

Alternatively, the flutter_phoenix package can be used for this purpose.

hacker1024
  • 3,186
  • 1
  • 11
  • 31
  • That seems like an interesting way of doing it. Resetting the whole app is a big it a sledgehammer solution, but I will look into the option of using a new Key. I must confess, I haven’t needed to delve into the subject of Keys yet, but I’d say it’s time! Thank you! – Drew Moe Nov 04 '21 at 16:26
  • You don't need to restart the app, if you use the package it will only reset the children of the closest `Phoenix` widget. – hacker1024 Nov 05 '21 at 02:28
1
 setState(() {
                _variable = null;
              });