我刚开始学习颤振,我使用有状态的小部件下面的代码是 main.dart 文件
void main() {
runApp(App());
}
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: new Scaffold(backgroundColor: Colors.blueGrey.shade100,
body: Home.Homescreen(HomeText: "default",), //initially setting text to default
appBar: new AppBar(
centerTitle: true,
title: new Text("newApp",
textDirection: TextDirection.ltr,
style: TextStyle(fontSize:20 ,color: Colors.white)),
),
bottomNavigationBar: new BottomNavigationBar(items: [
new BottomNavigationBarItem(
icon: Icon(Icons.home),
title: new Text(
"Home",
textDirection: TextDirection.ltr,
)),
new BottomNavigationBarItem(
icon: Icon(Icons.face),
title: new Text(
"Profile",
textDirection: TextDirection.ltr,
)),
new BottomNavigationBarItem(
icon: Icon(Icons.exit_to_app),
title: new Text(
"Exit",
textDirection: TextDirection.ltr,
)),
],onTap: (int item){
if(item == 0){
setState(() {
Home.Homescreen(HomeText:'this is home'); /* this should change homescreen text but it still says default same for all the below as well*/
});
}
else if(item == 1){
setState(() {
Home.Homescreen(HomeText:'this is proile');
});
}
else if(item == 2){
setState(() {
Home.Homescreen(HomeText:'this is exit');
});
}
},),
));
}
}
在此调用了一个无状态小部件“App”,并且在 Scaffold 中的 _AppState 中,主体被分配给一个无状态小部件“HomeScreen”,该无状态小部件“HomeScreen”在底部导航栏下的 main 中导出为主页,这些项目被分配一个 int,在点击时应该更改 HomeText因此,但它没有更新,它在主屏幕上保持不变,只是说“默认”,这是它最初被调用的,下面的代码是 home_screen.dart 被称为
class Homescreen extends StatefulWidget{
Homescreen({this.HomeText}); // init hometext
String HomeText;
@override
_Homescreen createState() => _Homescreen();
}
class _Homescreen extends State<Homescreen>{
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
new Text(
widget.HomeText, // this is what should be updated when called
textDirection: TextDirection.ltr,
style: new TextStyle(fontSize: 30,color: Colors.black),
)
],
),
);
}
}
我不明白为什么当点击图标(底部导航条)时主页文本没有更新,我已经使用调试打印测试了它们返回 0,1,2 的值。所以,这至少是正确的。