Reputation: 1713
I have a Flutter app that starts like this :
void main() async {
// Check if user is logged in
runApp(
MaterialApp(
home: (isLoggedIn) ? MainPage() : PageLogin(),
),
);
}
My MainPage (and my LoginPage) are just 2 regular Stateful Widgets.
class MainPage extends StatefulWidget {
MainPage({Key key, this.selectedPageDefault = 0}) : super(key: key);
@override
_MainPageState createState() => _MainPageState();
}
Let's say I have 2 more pages, just like MainPage : PageOne
and PageTwo
.
When I click on a button on MainPage
, it takes me to PageOne
, and when I click on a button on PageOne
, it takes me to PageTwo
.
I go to them using :
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PageOne(), // Or PageTwo
),
);
Now, when I click on a button in PageTwo
, I want to go back to MainPage
.
I could use Navigator.of(context).popUntil(...)
, however it needs to use routes, and I did not go to MainPage
using a route.
This is just an example, but on the real app I have more than just 2 pages after MainPage
, so I can't just use pushReplacement
or a tricky way to achieve this.
How can I go back to MainPage
?
Upvotes: 1
Views: 9340
Reputation: 1971
You need to add settings like this
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MainPage(),
settings : RouteSettings()..name = 'MainPage',
),
);
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PageOne(),
settings : RouteSettings()..name = 'PageOne',
),
);
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PageTwo(),
settings : RouteSettings()..name = 'PageTwo',
),
);
and you can use this
Navigator.of(context).popUntil(ModalRoute.withName('MainPage'));
Upvotes: 7