当用户单击bottomNavigationBar项目时,我试图更新appbar文本,该项目也通过称为chooseTab()的函数呈现了主体。我已经将appBarText放置在choiceTab()函数内的开关盒中,但是setState直到第二次单击才更新appBar文本。即使渲染,它也会渲染appBar文本的先前值。主体渲染没有任何问题。
class HomeScreen extends StatefulWidget {
static const String id = 'home_screen';
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String _appBarText = 'Dashboard';
int _tabIndex = 0;
GlobalKey _bottomNavigationKey = GlobalKey();
chooseTab() {
switch (this._tabIndex) {
case 0:
_appBarText = 'Dashboard';
return new DashboardScreen();
break;
case 1:
_appBarText = 'Cards';
return new CardScreen();
break;
case 2:
_appBarText = 'Receipts';
return new ReceiptsScreen();
break;
case 3:
_appBarText = 'Settings';
return new SettingsScreen();
break;
}
}
@override
Widget build(BuildContext context) {
return Container(
decoration: kBackground,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Text(
_appBarText,
),
),
body: chooseTab(),
bottomNavigationBar: CurvedNavigationBar(
key: _bottomNavigationKey,
index: _tabIndex,
height: 70.0,
items: <Widget>[
Icon(Icons.home, size: 25),
Icon(Icons.credit_card, size: 25),
Icon(Icons.receipt, size: 25),
Icon(Icons.person, size: 25),
],
onTap: (int tappedIndex) {
setState(() {
this._tabIndex = tappedIndex;
});
},
color: Colors.grey[900],
buttonBackgroundColor: Colors.grey[900],
backgroundColor: Colors.transparent,
animationCurve: Curves.easeInOut,
animationDuration: Duration(milliseconds: 600),
),
),
);
}
}
这是因为当您触发setState
时,将重新渲染小部件树,但在_appBarText
显示后及其时间显示主体内容时,开关盒设置为AppBar
您可以像这样列出您的标题:
List<String> titles = [
'Dashboard',
'Cards',
'Receipts',
'Settings'
];
然后您的appBar
应该是这样的:
appBar: AppBar(
title: Text(
titles[_tabIndex],
),
),
并且尝试不使用this
关键字:)