[英]Flutter/Dart - How can I change the State of a StatefulWidget from another StatefulWidget in a different file?
[英]how to change the state of one statefulwidget from another in flutter?
我有一個有狀態的小部件,它有條件地在堆棧中渲染兩個孩子,我想改變第三個孩子的渲染條件。 任何想法?
父代碼:
class MapPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body:Body()
);
}
}
class Body extends StatefulWidget {
final String showScreen;
const Body({
Key key,
this.showScreen="post",
}) : super(key:key);
@override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
Widget _conditionedWidget(){
if(this.widget.showScreen=="map"){
return MapScreen();
}else if(this.widget.showScreen == "post"){
return PostScreen();
}
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
DrawerScreen(),
_conditionedWidget(),
],
);
}
}
子代碼
class DrawerScreen extends StatefulWidget {
@override
_DrawerScreenState createState() => _DrawerScreenState();
}
class _DrawerScreenState extends State<DrawerScreen> {
@override
Widget build(BuildContext context) {
return Container(
color:kPrimaryColor,
padding:EdgeInsets.only(top:70),
child:Column(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(width:20.0),
CircleAvatar(),
SizedBox(width:10.0),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Biswas Sampad',style:TextStyle(
color:Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0,
)),
Text('@biswassampad',style:TextStyle(
color:Colors.grey[200],
fontSize: 15.0,
))
],
)
],
),
Container(
padding: EdgeInsets.symmetric(horizontal: 20,vertical:20),
margin: EdgeInsets.symmetric(vertical:30),
child: Column(
children: <Widget>[
MenuButton(icon:Icons.style, name:'Explore',action:(){
print('showing maop');
}),
MenuButton(icon:Icons.tag_faces, name:'Profile',action:(){
print('showing profile');
}),
MenuButton(icon:Icons.people, name:'People',action:(){
print('showing People');
}),
MenuButton(icon:Icons.speaker_notes, name:'Messages',action:(){
print('showing messages');
}),
MenuButton(icon:Icons.notifications, name:'Notifications',action:(){
print('showing Notifications');
}),
MenuButton(icon:Icons.satellite,name:'Settings',action:(){
print('showing settings');
})
],
),
),
LogoutSection()
],
)
);
}
}
所以基本上我想從 DrawerScreen>MenuButton>action 更改父小部件的 showScreen 值?
任何想法如何做到這一點。! 提前致謝。
您可以在“DrawerScreen”小部件中使用Function ,如下所示:
將此代碼寫入 class 的 header 中:
final Function onChangeState = Function();
DrawerScreen({@rquired onChangeState});
並在 MenuButton 中調用onChangeState function,如下所示:
MenuButton(icon:Icons.satellite,name:'Settings',action:(){
widget.onChangeState("Settings");
})
並將Body小部件中的舊代碼更改為:
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
DrawerScreen(onChangeState : (newState){
setState(){
this.widget.showScreen = newState;
};
}),
_conditionedWidget(),
],
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.