Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a flutter Page (Widget) to initial state(state when the app was first Built)

Tags:

flutter

dart

Let's say I have a few sliders and switches on my page, I change their state and modify them, I understand that we do setState to show the changed state of the widget tree and rebuild it, but I would like to know if there's a way to undo all those changes and go back to the initial state (state the app was when it was first built)?

like image 651
Mahesh Jamdade Avatar asked Feb 27 '20 17:02

Mahesh Jamdade


2 Answers

If you want to do things out of the box

enter image description here


Short answer:

Use any of the below:

Navigator.pushReplacementNamed(context, '/currentRoute');
Navigator.popAndPushNamed(context, '/currentRoute');

Long answer:

void main() => runApp(MaterialApp(home: DummyWidget()));

class DummyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) => HomePage();
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _enabled = false; // For Switch
  double _value = 0; // For Slider

  // This is the trick!
  void _reset() {
    Navigator.pushReplacement(
      context,
      PageRouteBuilder(
        transitionDuration: Duration.zero,
        pageBuilder: (_, __, ___) => DummyWidget(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Switch(
            value: _enabled,
            onChanged: (newValue) => setState(() => _enabled = newValue),
          ),
          Slider(
            value: _value,
            onChanged: (newValue) => setState(() => _value = newValue),
          ),
          FlatButton(
            onPressed: _reset,
            child: Text('RESET'),
          ),
        ],
      ),
    );
  }
}

A better approach might be with keys. Here's the key approach

like image 199
CopsOnRoad Avatar answered Oct 20 '22 19:10

CopsOnRoad


A simple trick would be to pop and push with the same route. Like this:

Navigator.popAndPushNamed(context, "same_route");
like image 29
Mircea Dragota Avatar answered Oct 20 '22 18:10

Mircea Dragota