GlobalKey<_SonState> sonKey = GlobalKey();
/ / child component
import 'package:flutter/material.dart';
// The key is the sonKey variable
GlobalKey<_SonState> sonKey = GlobalKey();
class Son extends StatefulWidget {
Son({Key key}) : super(key: key);
@override
_SonState createState() => _SonState();
}
class _SonState extends State<Son> {
// The method to be called by the parent component
void sonFn() {
print('call sonFn');
}
@override
Widget build(BuildContext context) {
return Container(
child: Text('Child component')); }}Copy the code
/ / the parent component
import 'package:flutter/material.dart';
// Introduce the son component
import 'son.dart';
class Father extends StatefulWidget {
Father({Key key}) : super(key: key);
@override
_FatherState createState() => _FatherState();
}
class _FatherState extends State<Father> {
@override
Widget build(BuildContext context) {
return Column(
children: [
// sonKey is used to define sonKey
Son(key: sonKey),
// The trigger button calls the child component method
RaisedButton(
onPressed: () {
// Use the subcomponent method
sonKey.currentState.sonFn();
},
child: Text('Click I call child component method'), a)],); }}Copy the code