How to use BottomNavigationBar with Navigator?

后端 未结 6 780
北荒
北荒 2020-12-02 08:36

The Flutter Gallery example of BottomNavigationBar uses a Stack of FadeTransitions in the body of the Scaffold.

I

6条回答
  •  醉梦人生
    2020-12-02 09:00

    Here is example:

      int _currentIndex = 0;
    
    
      Route _getRoute(RouteSettings settings) {
        final initialSettings = new RouteSettings(
            name: settings.name,
            isInitialRoute: true);
    
        return new MaterialPageRoute(
            settings: initialSettings,
            builder: (context) =>
            new Scaffold(
              body: new Center(
                  child: new Container(
                      height: 200.0,
                      width: 200.0,
                      child: new Column(children: [
                        new Text(settings.name),
                        new FlatButton(onPressed: () =>
                            Navigator.of(context).pushNamed(
                                "${settings.name}/next"), child: new Text("push")),
                      ],
                      ))
              ),
              bottomNavigationBar: new BottomNavigationBar(
                  currentIndex: _currentIndex,
                  onTap: (value) {
                    final routes = ["/list", "/map"];
                    _currentIndex = value;
                    Navigator.of(context).pushNamedAndRemoveUntil(
                        routes[value], (route) => false);
                  },
                  items: [
                    new BottomNavigationBarItem(
                        icon: new Icon(Icons.list), title: new Text("List")),
                    new BottomNavigationBarItem(
                        icon: new Icon(Icons.map), title: new Text("Map")),
                  ]),
            ));
      }
    
      @override
      Widget build(BuildContext context) =>
          new MaterialApp(
            initialRoute: "/list",
            onGenerateRoute: _getRoute,
            theme: new ThemeData(
              primarySwatch: Colors.blue,
            ),
          );
    

    You can set isInitialRoute to true and pass it to MaterialPageRoute. It will remove pop animation.

    And to remove old routes you can use pushNamedAndRemoveUntil

    Navigator.of(context).pushNamedAndRemoveUntil(routes[value], (route) => false);
    

    To set current page you can have a variable in your state _currentIndex and assign it to BottomNavigationBar:

提交回复
热议问题