我是新手,尝试在演示应用程序中实现BottomNavigationBar。底部栏确实显示在应用程序中,但是在点击时无法更改当前项目,屏幕也不会更改。
我尝试了各种方法来加载屏幕,但是好像没有调用onTap函数。
这是我的代码。
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
int _currentTab = 0;
Widget body() {
switch (_currentTab) {
case 0:
return FeedScreen();
case 1:
return SearchScreen();
case 2:
return ProfileScreen();
default:
return FeedScreen();
}
}
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
onTap: (newValue) {
setState(() {
_currentTab = newValue;
});
},
currentIndex: _currentTab,
items: [
BottomNavigationBarItem(
icon: ImageIcon(
AssetImage('images/home.png'),
),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: ImageIcon(
AssetImage('images/search.png'),
),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: CircleAvatar(
radius: 15,
backgroundImage: AssetImage('images/avatar.png'),
),
title: SizedBox.shrink(),
)
],
),
appBar: PreferredSize(
preferredSize: Size(screenSize.width, 50.0),
child: CustomAppBar(),
),
body: body(),
);
}
}
答案 0 :(得分:1)
您的int _currentTab = 0;
在build
方法内。放在外面。
每次触发setState
时,_currentTab
将始终等于0
的{{1}},因为变量位于FeedScreen
方法内部>
答案 1 :(得分:0)
尝试以下代码!
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _currentTab = 0;
@override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
Widget body() {
switch (_currentTab) {
case 0:
return FeedScreen();
case 1:
return SearchScreen();
case 2:
return ProfileScreen();
default:
return FeedScreen();
}
}
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
onTap: (newValue) {
setState(() {
_currentTab = newValue;
});
},
currentIndex: _currentTab,
items: [
BottomNavigationBarItem(
icon: ImageIcon(
AssetImage('images/home.png'),
),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: ImageIcon(
AssetImage('images/search.png'),
),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: CircleAvatar(
radius: 15,
backgroundImage: AssetImage('images/avatar.png'),
),
title: SizedBox.shrink(),
)
],
),
appBar: PreferredSize(
preferredSize: Size(screenSize.width, 50.0),
child: CustomAppBar(),
),
body: body(),
);
}
}
在构建方法之外写入int _currentTab = 0
,因为将newValue更新到_currentTab
时,setState
也重新分配了0值。