我有一个Flutter应用,它的启动方式如下:
void main() async {
// Check if user is logged in
runApp(
MaterialApp(
home: (isLoggedIn) ? MainPage() : PageLogin(),
),
);
}
我的MainPage(和LoginPage)只是2个常规的有状态小部件。
class MainPage extends StatefulWidget {
MainPage({Key key, this.selectedPageDefault = 0}) : super(key: key);
@override
_MainPageState createState() => _MainPageState();
}
假设我还有2页,就像MainPage一样:PageOne
和PageTwo
。
当我单击MainPage
上的按钮时,它将带我到PageOne
,而当我单击PageOne
上的按钮时,它将带我到PageTwo
。
我使用:
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PageOne(), // Or PageTwo
),
);
现在,当我单击PageTwo
中的按钮时,我想返回到MainPage
。
我可以使用Navigator.of(context).popUntil(...)
,但是它需要使用路由,而我没有使用路由去MainPage
。
这只是一个例子,但是在真实应用中,MainPage
之后我只有两页,所以我不能仅仅使用pushReplacement
或一种棘手的方法来实现这一目标。
如何返回MainPage
?
答案 0 :(得分:1)
您需要添加这样的设置
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',
),
);
您可以使用此
Navigator.of(context).popUntil(ModalRoute.withName('MainPage'));
答案 1 :(得分:1)
使用此Navigator.of(context).popUntil((route) => route.isFirst)