首页 > 解决方案 > Flutter:如何将带参数的函数传递给子类

问题描述

如何将带参数的函数传递给 Flutter 中的子类?

我当前的代码如下所示。

parent.dart

class _ParentState extends State<Parent> {
    int _currentIndex = 0;

    Widget callPage(int currentIndex) {
      switch (currentIndex) {
        case 0:
         return Child(
          aFunction: _aFunction('hello')
        );
      case 1:
        return Child1();
      case 2:
        return Child2();
      default:
        return Child();
      }

    }

  @override
  Widget build(Buildcontext context) {
      ...
  }

  Future<void> _aFunction(String arg) async {
      ...
  }
}

child.dart

class Child extends StatefulWidget {
    final Function(String hello) aFunction;

    Child({this.aFunction});
}


...

class _ChildState extends State<Child> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.0),
      child: RefreshIndicator(
        onRefresh: widget.aFunction, // How can I refer to the argument here?

我不知道该怎么做,但无论如何我都尝试过这种方式,并且 Parent 类中有错误。它说

参数类型 Future 不能分配给参数类型“动态函数(字符串)”

标签: flutterdart

解决方案


只需传递函数的引用,如下所示。您不必添加字符串参数_aFunction("hello")

Widget callPage(int currentIndex) {
      switch (currentIndex) {
        case 0:
         return Child(
          aFunction: _aFunction
        );
      case 1:
        return Child1();
      case 2:
        return Child2();
      default:
        return Child();
      }

    }

然后您可以从子小部件中调用该函数

RefreshIndicator(child: Container(), onRefresh: widget.aFunction("Hello")

推荐阅读