flutter 父组件调用子组件方法

标题在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'),
        ),
      ],
    );
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值