基本上,我有一个主要的小部件,它有一个
听起来很完美,但它不能正常工作。
当我点击更改所选选项时,它会更改屏幕,但所选图标保持不变。如果我打印
因此,我意识到我可能忘记在onTap上使用
我不知道为什么会发生这种情况。也许是关于
this._bottomNavigationBar
,当屏幕更改时,我将其传递给新屏幕。然后,每个屏幕都有自己的Scaffold
和AppBar
。听起来很完美,但它不能正常工作。
当我点击更改所选选项时,它会更改屏幕,但所选图标保持不变。如果我打印
this.currentIndex
,它通常会更改索引。这是我没有预料到的,因为当我声明this._bottomNavigationBar
时,currentIndex
属性是这样定义的:currentIndex: this.currentIndex
,因此如果图标不更改,则变量也不会更改。因此,我意识到我可能忘记在onTap上使用
setState()
方法,但事实并非如此。我不知道为什么会发生这种情况。也许是关于
setState
“范围”的问题?我将在下面留下我的代码以更好地说明这一点。
home.dart
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'landing.dart';
const List<BottomNavigationBarItem> homeScreenNavbarItems = [
BottomNavigationBarItem(
icon: Icon(FontAwesomeIcons.home),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.bookmark),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text(''),
),
];
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeState();
}
}
class _HomeState extends State<Home> {
int currentIndex = 1;
BottomNavigationBar _bottomNavigationBar;
List homeScreens;
void onNavbarTapped(int index) {
setState(() {
this.currentIndex = index;
});
}
@override
void initState() {
this._bottomNavigationBar = BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
selectedItemColor: Color(0xFF000000),
unselectedItemColor: Color(0xFFb3b3b3),
currentIndex: this.currentIndex,
items: homeScreenNavbarItems,
onTap: this.onNavbarTapped,
);
this.homeScreens = [
LandingScreen(this._bottomNavigationBar),
Scaffold(
bottomNavigationBar: this._bottomNavigationBar,
)
];
super.initState();
}
@override
Widget build(BuildContext context) {
print(this.currentIndex);
return this.homeScreens.elementAt(this.currentIndex);
}
}
landing.dart
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class LandingScreen extends StatefulWidget {
final BottomNavigationBar _bottomNavigationBar;
LandingScreen(this._bottomNavigationBar);
@override
State<StatefulWidget> createState() {
return _LandingScreenState();
}
}
class _LandingScreenState extends State<LandingScreen> {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: Text('a'),
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
),
body: TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
bottomNavigationBar: widget._bottomNavigationBar,
),
);
}
}
main.dart
文件只是调用Home
小部件,所以我没有将它放在这里。