How do I access a method of the state objects for a list of stateful widgets? (Flutter) How do I access a method of the state objects for a list of stateful widgets? (Flutter) dart dart

How do I access a method of the state objects for a list of stateful widgets? (Flutter)


You can use a GlobalKey with the Widget's state to access the child Widget's methods:

class Main extends StatefulWidget {  @override  _MainState createState() => _MainState();}class _MainState extends State<Main> {  GlobalKey<_HomeState> _key = GlobalKey();  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title: Text('StackOverflow'),      ),      body: Column(        mainAxisAlignment: MainAxisAlignment.center,        children: <Widget>[          Home(key: _key),          RaisedButton(            onPressed: () => _key.currentState.changeText('new text'),            child: Text('Change text'),          )        ],      )    );  }}class Home extends StatefulWidget {  Home({Key key}) : super(key: key);  @override  _HomeState createState() => _HomeState();}class _HomeState extends State<Home> {  String text = 'initial text';  @override  Widget build(BuildContext context) {    return Center(      child: Text(text)    );  }  void changeText(String newText){    setState(() {      text = newText;    });  }}