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
?
Use this Navigator.of(context).popUntil((route) => route.isFirst)