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)?
If you want to do things out of the box
Use any of the below:
Navigator.pushReplacementNamed(context, '/currentRoute');
Navigator.popAndPushNamed(context, '/currentRoute');
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
A simple trick would be to pop and push with the same route. Like this:
Navigator.popAndPushNamed(context, "same_route");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With