I have two widgets. Both are stateful widgets.I put a button and Child widget in HomePage widget. I want to change counter variable in Child widget from HomePage widget when click on button in HomePage widget. I should use setState method for that but I can't call it outside from Child widget.What is the proper way to do that?
Parent
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Child(),
FlatButton(
onPressed: () {
//Increase Child widget's counter variable
},
child: Text("Button In Parent"),
color: Colors.amber,
)
],
),
);
}
}
Child
class Child extends StatefulWidget {
@override
_ChildState createState() => _ChildState();
}
class _ChildState extends State<Child> {
int counter = 0;
@override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Text In Child: ',
style: TextStyle(fontSize: 30),
),
Text(
//Increase this variable from parent
counter.toString(),
style: TextStyle(fontSize: 50),
),
],
),
),
);
}
}
question from:
https://stackoverflow.com/questions/65837199/modify-value-in-statefull-child-widget-from-its-statefull-parent 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…