标题在Flutter中,父组件可以通过GlobalKey来引用子组件,并调用子组件的方法。以下是一个简单的例子:
在这个例子中,ParentComponent 有一个GlobalKey,它被传递给了ChildComponent。当按钮被点击时,通过childKey.currentState我们调用了ChildComponent状态中的doSomething方法。
1.首先,定义一个子组件并且在其状态中定义一个方法:
import 'package:flutter/material.dart';
class ChildComponent extends StatefulWidget {final GlobalKey key;ChildComponent({this.key}) : super(key: key); _ChildComponentState createState() => _ChildComponentState();
}class _ChildComponentState extends State<ChildComponent> {void doSomething() {print('Doing something in the child component.');}Widget build(BuildContext context) {return Container(); // 子组件的构建代码}
}
在父组件中创建一个GlobalKey并将其传递给子组件:
import 'package:flutter/material.dart';class ParentComponent extends StatefulWidget { _ParentComponentState createState() => _ParentComponentState();
}class _ParentComponentState extends State<ParentComponent> {final GlobalKey<_ChildComponentState> childKey = GlobalKey();Widget build(BuildContext context) {return Column(children: <Widget>[ChildComponent(key: childKey),RaisedButton(onPressed: () => childKey.currentState.doSomething(),child: Text('Call Child Method'),),],);}
}