我正在开发一个扑朔迷离的项目,它包含许多屏幕。因此,我将底部导航栏分解为一个单独的小部件,并在每个屏幕上重复使用了它。当我导航到另一个屏幕时,底部导航栏未突出显示为活动状态。
nav_bar.dart
import 'package:flutter/material.dart';
class BottomNavigation extends StatefulWidget {
@override
_BottomNavigationState createState() => _BottomNavigationState();
}
class _BottomNavigationState extends State<BottomNavigation> {
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [themeColor, themeColorLight],
),
),
child: BottomNavigationBar(
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
iconSize: 28,
fixedColor: Colors.white,
elevation: 0,
backgroundColor: Colors.transparent,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.dashboard),
title: Text('For you'),
),
BottomNavigationBarItem(
icon: Icon(Icons.camera, size: 55),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
title: Text('Health'),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text('Profile'),
),
],
//Navigation On Tap
onTap: (index) {
setState(() {
_currentIndex = index;
switch (index) {
case 0:
{
Navigator.pushNamed(context, '/home');
}
break;
case 1:
{
Navigator.pushNamed(context, '/signup');
}
break;
case 2:
{
Navigator.pushNamed(context, '/camera');
}
break;
case 3:
{
Navigator.pushNamed(context, '/assistant');
}
break;
case 4:
{
Navigator.pushNamed(context, '/profile');
}
}
});
}, //OnTap Method Ends
),
);
}
}
这就是我在屏幕上调用小部件的方式。
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBar(),
body: Container(),
bottomNavigationBar: BottomNavigation(),
);
}
router.dart
class Router {
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (_) => HomeScreen());
case '/signup':
return MaterialPageRoute(builder: (_) => SignupScreen());
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}'),
),
),
);
}
}
}
答案 0 :(得分:0)
这样做的原因是每次切换屏幕时都会重建BottomNavigationBar
,因此状态会丢失。您必须传入一个显示屏幕的变量。我通常会创建enums,因此当我创建带有底部栏的屏幕时,它将看起来像这样:
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBar(),
body: Container(),
bottomNavigationBar: BottomNavigation(screen: ScreenTypes.Home),
);
}
然后在您的BottomNavigationBar
中使用您创建的该枚举作为索引。