How to use BottomNavigationBar with Navigator?

后端 未结 6 782
北荒
北荒 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 08:52

    The Complete Example

    First make a class MyBottomBarDemo

    class MyBottomBarDemo extends StatefulWidget {
      @override
      _MyBottomBarDemoState createState() => new _MyBottomBarDemoState();
    }
    
    class _MyBottomBarDemoState extends State {
      int _pageIndex = 0;
      PageController _pageController;
    
      List tabPages = [
        Screen1(),
        Screen2(),
        Screen3(),
      ];
    
      @override
      void initState(){
        super.initState();
        _pageController = PageController(initialPage: _pageIndex);
      }
    
      @override
      void dispose() {
        _pageController.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("BottomNavigationBar", style: TextStyle(color: Colors.white)),
            backgroundColor: Colors.deepPurple,
          ),
          bottomNavigationBar: BottomNavigationBar(
            currentIndex: _pageIndex,
            onTap: onTabTapped,
            backgroundColor: Colors.white,
            items: [
              BottomNavigationBarItem( icon: Icon(Icons.home), title: Text("Home")),
              BottomNavigationBarItem(icon: Icon(Icons.mail), title: Text("Messages")),
              BottomNavigationBarItem(icon: Icon(Icons.person), title: Text("Profile")),
            ],
    
          ),
          body: PageView(
            children: tabPages,
            onPageChanged: onPageChanged,
            controller: _pageController,
          ),
        );
      }
      void onPageChanged(int page) {
        setState(() {
          this._pageIndex = page;
        });
      }
    
      void onTabTapped(int index) {
        this._pageController.animateToPage(index,duration: const Duration(milliseconds: 500),curve: Curves.easeInOut);
      }
    }
    

    Then create a your screens

    class Screen1 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Container(
            color: Colors.green,
                child: Center(child: Text("Screen 1")),
        );
      }
    }
    
    class Screen2 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Container(
          color: Colors.yellow,
          child: Center(child: Text("Screen 2")),
        );
      }
    }
    
    class Screen3 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Container(
          color: Colors.cyan,
          child: Center(child: Text("Screen 3")),
        );
      }
    }
    

提交回复
热议问题