我是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'),
),
],
);
}
}
```
You forgot to call
setState
in your_onItemTapped
function.To fix this problem, replace the code below with your
_onItemtapped
function:我希望这有帮助。