简体   繁体   English

如何访问状态对象的方法以获取有状态小部件列表? (扑)

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

class Astate extends State<A>
{
   List b=new List<B>();
   @override
   Widget build(BuildContext context){

       b.add(B());  
      //how do I access theMethod() for the state object for b[0]?

    }
}

class B extends StatefulWidget
{
      @override
      Bstate createState() => Bstate();
}

class Bstate extends State<B>
{
    theMethod()
     { 
        //some content
     }

  @override
  Widget build(BuildContext context) {
   }

}

Is there a way to access the theMethod() using b[0] from it's corresponding state object?有没有办法从对应的状态对象中使用 b[0] 访问 theMethod() ? If not, is there another way to achieve the same?如果没有,是否有另一种方法可以实现相同的目标?

You can use a GlobalKey with the Widget's state to access the child Widget's methods:您可以使用具有 Widget 状态的 GlobalKey 来访问子 Widget 的方法:

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;
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM