flutter - Flutter 的 BottomNavigationBar 未在点击时更新所选项目
问题描述
我是 Flutter 的新手,目前正在尝试非常简单的练习来了解基础知识。我刚刚在屏幕底部创建了一个带有 BottomNavigationBar 的基本 Home。但是当我点击一个条形图标时,它不会切换颜色以使其看起来好像被点击了一样。我需要重新加载它以更新它。我无法从“ MyBottmNavigationBar ”类更新图标状态...如果我只是复制/粘贴 Flutter.dev 示例代码它可以工作...我需要在我的代码中修复什么?随时指出任何错误或提示!提前致谢!
import 'package:flutter/material.dart';
void main()=> runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Home();
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyScaffold(),
);
}
}
class MyScaffold extends StatefulWidget {
@override
_MyScaffoldState createState() => _MyScaffoldState();
}
class _MyScaffoldState extends State<MyScaffold> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Hey Flutter'),),
body: MyListView(),
bottomNavigationBar: MyBottomNavigationBar(),
);
}
}
class MyListView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.all(2),
children: <Widget>[
Container(
height: 50,
color: Colors.amber[600],
child: const Center(child: Text('Entry A')),
),
Container(
height: 50,
color: Colors.amber[500],
child: const Center(child: Text('Entry B')),
),
Container(
height: 50,
color: Colors.amber[100],
child: const Center(child: Text('Entry C')),
),
Container(
height: 50,
color: Colors.amber[600],
child: const Center(child: Text('Entry A')),
),
],
);
}
}
class MyBottomNavigationBar extends StatefulWidget {
MyBottomNavigationBar({Key key}) : super(key: key);
@override
_MyBottomNavigationBarState createState() => _MyBottomNavigationBarState();
}
class _MyBottomNavigationBarState extends State<MyBottomNavigationBar> {
int _selectedIndex = 0;
void _onItemTapped(int index){
_selectedIndex = index;
print('Selected: ${_selectedIndex} CurrentIndex: ${index}');
}
@override
Widget build(BuildContext context) {
return BottomNavigationBar(
currentIndex: _selectedIndex,
selectedItemColor: Colors.pink,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.table_chart),
title: Text('Projects'),
),
BottomNavigationBarItem(
icon: Icon(Icons.people),
title: Text('Teams'),
),
],
);
}
}
```
解决方案
此外,不要在 build 方法中编写 ontapped() ,因为它创建了相同的实例并且从不更新视图。
推荐阅读
- java - 为什么 List.contains(Object) 的行为不同?
- r - 如何在同一个数据帧上做colsum和average
- powerbi - 使用 DAX 生成日期系列
- javascript - 仅在服务器上需要一个包
- java - Intellij IDEA 仅针对所有未提交的更改运行测试
- regex - 在换行符之前匹配字符,不包括空格?
- macos - MacOS - 使用带有launchd的脚本 - 启动,登录,注销,关闭?
- service-worker - Workbox 的服务人员在更改时未更新
- python - AllenNLP 共指分辨率的多 GPU 训练
- reactjs - 事件处理程序中带有 [name] 的 PrevState