Flutter 父组件调用子组件方法

7,101 阅读1分钟

重点是这句: GlobalKey<_SonState> sonKey = GlobalKey();

// 子组件
import 'package:flutter/material.dart';

// 重点是 sonKey 变量
GlobalKey<_SonState> sonKey = GlobalKey();

class Son extends StatefulWidget {
  Son({Key key}) : super(key: key);

  @override
  _SonState createState() => _SonState();
}

class _SonState extends State<Son> {
// 需要被父组件调用的方法
  void sonFn() {
    print('call sonFn');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text('子组件'),
    );
  }
}

// 父组件
import 'package:flutter/material.dart';
// 引入 son 组件
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: [
        // key使用定义sonKey
        Son(key: sonKey),
        // 触发按钮调用子组件方法
        RaisedButton(
          onPressed: () {
            // 使用子组件方法
            sonKey.currentState.sonFn();
          },
          child: Text('点击我调用子组件方法'),
        )
      ],
    );
  }
}