【发布时间】: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 != null
是false。我怎样才能避免这种情况?
【问题讨论】:
标签: flutter dart navigation bottomnavigationview