Drew Moe
Drew Moe

Reputation: 79

Resetting a variable in Flutter

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;
              });
            },
          )
        ],
      ),
    );
  }
}

Upvotes: 0

Views: 4159

Answers (2)

user15881299
user15881299

Reputation:

 setState(() {
                _variable = null;
              });

Upvotes: 1

hacker1024
hacker1024

Reputation: 3668

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.

Upvotes: 1

Related Questions