颤振-弹出直到没有路线的屏幕

时间:2020-05-29 00:17:27

标签: flutter dart flutter-navigation

我有一个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一样:PageOnePageTwo
当我单击MainPage上的按钮时,它将带我到PageOne,而当我单击PageOne上的按钮时,它将带我到PageTwo
我使用:

Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageOne(), // Or PageTwo
  ),
);

现在,当我单击PageTwo中的按钮时,我想返回到MainPage
我可以使用Navigator.of(context).popUntil(...),但是它需要使用路由,而我没有使用路由去MainPage

这只是一个例子,但是在真实应用中,MainPage之后我只有两页,所以我不能仅仅使用pushReplacement或一种棘手的方法来实现这一目标。

如何返回MainPage

2 个答案:

答案 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)