【问题标题】:How to switch BottomNavigationBar tabs Programmatically in flutter (and Navigate between pages)如何在颤动中以编程方式切换 BottomNavigationBar 选项卡(以及在页面之间导航)
【发布时间】:2021-05-24 14:15:31
【问题描述】:

我正在使用相当新的颤振。所以任何好的建议都会对我有所帮助。

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

我正在使用 curved_navigation_bar [https://pub.dev/packages/curved_navigation_bar] 包作为我的 BottomNavigationBar

HomeView.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 文件来管理我的应用中的导航。

NavBar.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() 函数时(不是通过单击底部导航选项卡)事情变得很奇怪。

下面是gif链接MyApp

标签应该更改,因为我没有将状态更改为_sessionDetails.file != nullfalse。我怎样才能避免这种情况?

【问题讨论】:

    标签: flutter dart navigation bottomnavigationview


    【解决方案1】:

    在changeTab中你需要使用key来改变页面:

    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);
                      },
                    )
                  ],
                ),
              ),
            ));
      }
    

    【讨论】:

    • 我已经更新了答案,你应该按照作者提供的方式进行
    猜你喜欢
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多