【发布时间】:2021-04-24 17:58:34
【问题描述】:
我希望 BottomNavigationBar 保持不变,并将用户发送到不同的屏幕,具体取决于他们选择的索引以及在 BottomNavigationBar 上突出显示的索引。
我尝试这样做的方法是根据BottomNavigationBar() 的当前选定索引更改Scaffold 的主体值。我可以突出显示 BottomNavigationBar() 的选定索引,一旦它被选中,但正文没有路由到适当的小部件。
BottomNavBar 中 onTap: 引用的当前方法正确突出显示所选索引,但未路由到正确的小部件。
我的BottomNavBar 中有一个未使用的方法 (_switchScreen)。将此作为onTap: 的值插入BottomNavBar() 会适当地路由到正确的屏幕,但随后我必须在每个视图上重建BottomNavBar,并且在BottomNavBar 后面无法访问NavModel 中引用的BottomNavBar (导航模型)。
这是我的BottomNavBar():
import 'package:flutter/material.dart';
import '../screens/Add_Media_Screen.dart';
import '../screens/Profile_Screen.dart';
import '../screens/Venture_Feed_Screen.dart';
class BottomNavBar extends StatefulWidget {
@override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _selectedIndex = 0;
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
void _switchScreen(index) {
switch (index) {
case 0:
Navigator.pushNamed(context, VentureFeedScreen.routeName);
break;
case 1:
Navigator.pushNamed(context, ProfileScreen.routeName);
break;
case 2:
Navigator.pushNamed(context, AddMediaScreen.routeName);
break;
}
}
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(
primaryColor: Color(0xff84d1da),
accentColor: Color(0xff62c2a2),
),
child: BottomNavigationBar(
selectedItemColor: Color(0xff84d1da),
unselectedItemColor: Colors.grey,
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
//Index 0
BottomNavigationBarItem(
icon: Icon(
Icons.explore,
),
label: 'Discover',
),
//Index 1
BottomNavigationBarItem(
icon: Icon(
Icons.account_circle,
// color: Color(0xff84d1da),
),
label: 'Profile',
// backgroundColor: Color(0xff84d1da),
),
//Index 2
BottomNavigationBarItem(
icon: Icon(
Icons.add_circle_outline,
),
label: 'Add Media',
),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
);
}
}
这里是NavModel:
import 'package:flutter/material.dart';
import '../screens/Profile_Screen.dart';
import '../screens/Venture_Feed_Screen.dart';
import '../screens/Add_Media_Screen.dart';
import '../widgets/BottomNavBar.dart';
class NavModel extends StatefulWidget {
static const routeName = '/nav-model';
@override
_NavModelState createState() => _NavModelState();
}
class _NavModelState extends State<NavModel> {
int _currentIndex = 0;
final tabs = [
VentureFeedScreen(),
ProfileScreen(),
AddMediaScreen(),
];
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: tabs[_currentIndex],
bottomNavigationBar: BottomNavBar(),
),
);
}
}
【问题讨论】:
标签: flutter dart bottomnavigationview flutter-scaffold