constructor - Dart (/flutter ): Create function in initializer list

标签 constructor dart flutter initializer-list function-object

我正在实现一个具有多个构造函数的类,它在内部围绕 IndexedWidgetBuilder(一个函数对象)构建

typedef IndexedWidgetBuilder = Widget Function(BuildContext context, int index);

现在,调用它的构造函数之一 MyWidget.list 将接收一个列表 myList 并从中创建 IndexedWidgetBuilder myBuilder:

IndexedWidgetBuilder myBuilder
  = (BuildContext context, int index) => list[index % list.length];

虽然这个代码片段单独运行完美,但我无法在构造函数的初始化列表中使用它。一个最小的工作示例读取

class MyApp {
  // Default constructor goes here

  MyApp.list(List<int> myList) :
    myBuilder = (BuildContext context, int index) => list[index % list.length];

  final IndexedWidgetBuilder myBuilder;
}

在 Android Studio 中,这段代码会产生错误:

The initializer type 'Type' can't be assigned to the field type '(BuildContext, int) → Widget'.

我没有在谷歌上找到任何相关的东西,语言文档也没有提供有用的信息。删除 final 关键字并将所有内容移动到构造函数的代码块中将是一种解决方案,尽管我只会考虑最后的手段。


注意:这不是一个直接的抖动问题,因为它会出现在每个函数对象中。

最佳答案

将函数括在括号中似乎可以使警告消失;尽管将其更改为说括号是多余的!

  MyApp.list(List<Widget> list)
      : myBuilder =
            ((_, int index) => list[index % list.length]);

注意上下文是如何未被使用的。这意味着您的预构建小部件无法访问它,这意味着它们不能将它用于任何 .of() 派生用途。

关于constructor - Dart (/flutter ): Create function in initializer list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582375/

相关文章:

flutter - 绘制一个带边框的椭圆来显示图像

Flutter ios 卡在 'Configuring the default Firebase app'

flutter - 在Flutter中使用BottomNavigationBar浏览页面时的标准做法?

javascript - 如何在聚合物元素中使用来自 Dart 的 javascript

flutter 网络 : unhandled element filter on svg

android-studio - Flutter:当您离开屏幕或按回时如何摆脱小部件?

java - 如何在 Google App Engine 中正确初始化/定义 Text 类的对象?

c++ - 在 C++ 中,是否可以在构造函数中访问静态变量?

scala - 为什么我不能在 Scala 子类中分配给 var?

c++ - 关于编译时 1.constructor 和 2.array 定义的一些疑问