Flutter persistent navigation bar with named route

2019-05-08 11:39发布

问题:

I've been searching around for a good navigation/router example for Flutter but I have not managed to find one.

What I want to achieve is very simple:

  1. Persistent bottom navigation bar that highlights the current top level route
  2. Named routes so I can navigate to any route from anywhere inside the app
  3. Navigator.pop should always take me to the previous view I was in

The official Flutter demo for BottomNavigationBar achieves 1 but back button and routing dont't work. Same problem with PageView and TabView. There are many other tutorials that achieve 2 and 3 by implementing MaterialApp routes but none of them seem to have a persistent navigation bar.

Are there any examples of a navigation system that would satisfy all these requirements?

回答1:

What you are asking for would violate the material design specification.

On Android, the Back button does not navigate between bottom navigation bar views.

A navigation drawer would give you 2 and 3, but not 1. It depends on what's more important to you.

You could try using LocalHistoryRoute. This achieves the effect you want:

class MainPage extends StatefulWidget {
  @override
  State createState() {
    return new MainPageState();
  }
}

class MainPageState extends State<MainPage> {
  int _currentIndex = 0;
  List<int> _history = [0];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Bottom Nav Back'),
      ),
      body: new Center(
        child: new Text('Page $_currentIndex'),
      ),
      bottomNavigationBar: new BottomNavigationBar(
        currentIndex: _currentIndex,
        items: <BottomNavigationBarItem>[
          new BottomNavigationBarItem(
            icon: new Icon(Icons.touch_app),
            title: new Text('keypad'),
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.assessment),
            title: new Text('chart'),
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.cloud),
            title: new Text('weather'),
          ),
        ],
        onTap: (int index) {
          _history.add(index);
          setState(() => _currentIndex = index);
          Navigator.push(context, new BottomNavigationRoute()).then((x) {
            _history.removeLast();
            setState(() => _currentIndex = _history.last);
          });
        },
      ),
    );
  }
}

class BottomNavigationRoute extends LocalHistoryRoute<void> {}


回答2:

CupertinoTabBar behave exactly same as you described, but in iOS style. It can be used in MaterialApps however.

Sample Code



标签: dart flutter