繁体   English   中英

如何在 flutter 中以编程方式切换 BottomNavigationBar 选项卡(以及在页面之间导航)

[英]How to switch BottomNavigationBar tabs Programmatically in flutter (and Navigate between pages)

我正在使用 flutter 的新手。所以任何好的建议都会对我有所帮助。

我正在创建一个具有三个页面的应用程序 - 一个主页、一个详细信息页面和一个设置页面。 所以在我的主页代码中,提交一些数据后,用户将被带到第二页(即详细信息页面)

我使用curl_navigation_bar [ https://pub.dev/packages/curved_navigation_bar ] package 作为我的 BottomNavigationBar

主页查看.dart

import 'package:curved_navigation_bar/curved_navigation_bar.dart';
//necessary imports

class HomeView extends StatefulWidget {
  final GlobalKey globalKey;

  HomeView(this.globalKey);

  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: //SomeButton(
        onPressed: () => {
          final CurvedNavigationBar navigationBar = widget.globalKey.currentWidget;
          navigationBar.onTap(1);  //<-This is the line where user will be taken to page 2
        }
      ),
    );
  }
}

现在我制作了一个NavBar.dart文件来管理我的应用程序中的导航。

导航栏.dart

import 'package:curved_navigation_bar/curved_navigation_bar.dart';
//necessary imports

class NavBar extends StatefulWidget {
  NavBar({Key key}) : super(key: key);

  @override
  _NavBarState createState() => _NavBarState();
}

class _NavBarState extends State<NavBar> {
  GlobalKey globalKey = new GlobalKey(debugLabel: 'btm_app_bar');
  ChatSessionDetails _chatSessionDetails = ChatSessionDetails();

  int _currentIndex;
  String _appBarTitle;

  List<Widget> pages = [];

  final PageStorageBucket bucket = PageStorageBucket();

  void initState() {
    super.initState();

    pages = [
      HomeView(globalKey),
      ChatView(key: PageStorageKey('ChatPage')),
      SettingsView()
    ];

    _currentIndex = 0;
    _appBarTitle = 'HomePage';
  }

  void changeTab(int index) {      //<-PageChange logic
    switch (index) {
      case 0:
        setState(
          () => {
            _appBarTitle = 'HomePage',
            _currentIndex = 0,
          },
        );
        break;
      case 1:
        if (_sessionDetails.file != null) {
          setState(
            () => {
              _appBarTitle = //some title,
              _currentIndex = 1
            },
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content: Text('You haven\'t opened a session yet'),
            behavior: SnackBarBehavior.floating,
          ));
        }
        break;
      case 2:
        setState(
          () => {
            _appBarTitle = 'Settings',
            _currentIndex = 2,
          },
        );
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_appBarTitle),
      ),
      body: PageStorage(
        child: pages[_currentIndex],
        bucket: bucket,
      ),
      extendBody: true,
      bottomNavigationBar: CurvedNavigationBar(
        key: globalKey,        items: <Widget>[
          Icon(Icons.home_rounded, size: 30, color: Colors.grey[600]),
          Icon(CustomIcons.whatsapp, size: 30, color: Colors.grey[600]),
          Icon(Icons.settings_rounded, size: 30, color: Colors.grey[600]),
        ],
        onTap: (index) {
          changeTab(index); //Handle button tap
        },
      ),
    );
  }
}

整个导航过程非常顺利,但是当我以编程方式调用changeTab() function 时(不是通过单击底部导航选项卡),事情变得很奇怪。

下面是 gif MyApp的链接

该选项卡应该更改,因为我没有将 state 更改为_sessionDetails.file != nullfalse 我怎样才能避免这种情况?

在 changeTab 中,您需要使用键来更改页面:

globalKey.currentState.setPage(1);

[更新]

作者官方方式:

以编程方式更改页面

  //State class
  int _page = 0;
  GlobalKey _bottomNavigationKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        bottomNavigationBar: CurvedNavigationBar(
          key: _bottomNavigationKey,
          items: <Widget>[
            Icon(Icons.add, size: 30),
            Icon(Icons.list, size: 30),
            Icon(Icons.compare_arrows, size: 30),
          ],
          onTap: (index) {
            setState(() {
              _page = index;
            });
          },
        ),
        body: Container(
          color: Colors.blueAccent,
          child: Center(
            child: Column(
              children: <Widget>[
                Text(_page.toString(), textScaleFactor: 10.0),
                RaisedButton(
                  child: Text('Go To Page of index 1'),
                  onPressed: () {
                    //Page change using state does the same as clicking index 1 navigation button
                    final CurvedNavigationBarState navBarState =
                        _bottomNavigationKey.currentState;
                    navBarState.setPage(1);
                  },
                )
              ],
            ),
          ),
        ));
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM