flutter - 导航后底部导航栏不突出显示活动屏幕
问题描述
我正在做一个颤振项目,它包含很多屏幕。所以我将底部导航栏分解为一个单独的小部件,并在每个屏幕上重复使用它。当我导航到另一个屏幕时,底部导航栏未突出显示为活动状态。
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(),
);
}
路由器.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}'),
),
),
);
}
}
}
解决方案
原因是BottomNavigationBar
每次切换屏幕时都会重建您的状态,因此状态会丢失。您必须传入一个显示屏幕的变量。我通常会创建枚举,因此当我使用底栏创建屏幕时,它看起来像这样:
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBar(),
body: Container(),
bottomNavigationBar: BottomNavigation(screen: ScreenTypes.Home),
);
}
然后在您BottomNavigationBar
使用您创建的这个枚举作为索引。
推荐阅读
- ruby-on-rails - Michael 的 Ruby on Rails 教程 - 第 -2 章玩具应用程序 - Puma 发现了这个错误:未初始化的常量 ApplicationController (NameError)
- google-chrome-devtools - “添加到主屏幕”链接在 Chrome Devtools - Application - Manifest 中不可见
- java - 适用于 Linux 和 Window 的 Java Spring 项目环境属性文件
- angular - 如何设置角度形式的验证器,如果它已经具有无效值,则检测到错误
- excel - VBA从XL复制范围并在PPT中粘贴“仅保留文本”
- javascript - 如何使图像适合 React/Bootstrap 中的页面?
- sql - SQL获取最接近数字的值
- mysql - Posgresql vs Mysql 用于基于 SqlAlchemy 的 RESTful API?
- vmware-clarity - Datagrid 排序号 - 最后希望为空
- .net-core - 看不到来自外部程序集的 Xml 注释