Issue
So I have this kind of walkthrough that pushes the user from one screen to another (Six screens in total). In the last page, I would like the user to press "Done" and take him back to the first screen without being able to pop back to any of the previous screens.
Right now it will pop the last screen but not any of the other ones so it take me back to my original screen with the ability to pop back to the screen before the last screen (hopefully that last sentence makes sense to you, because the last screen was popped it takes me back to the screen before that one).
Any idea how to get around that?
Thanks!
Solution
To pop multiple screens from the navigation stack, like in your given scenario we can use Navigator.popUntil. It takes a BuildContext
and a RoutePredicate
as parameters. The Navigator calls pop
until the returned value by the given RoutePredicate
is true.
Here is very basic example. It uses ModalRoute.withName to create the RoutePredicate
:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (BuildContext context) => Home(),
'/another': (BuildContext context) => Another()
},
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Home'),
RaisedButton(
child: Text('Take me to another screen!'),
onPressed: () => Navigator.pushNamed(context, '/another'),
)
],
),
),
);
}
}
class Another extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('Next screen.'),
onPressed: () => Navigator.pushNamed(context, '/another'),
),
RaisedButton(
child: Text('Pop em all.'),
onPressed: () => Navigator.popUntil(
context,
ModalRoute.withName('/'),
),
),
],
),
),
);
}
}
Answered By - NiklasPor
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.