[英]Dart(/Flutter): Create function in initializer list
I am implementing a class with multiple constructors, which is internally build around a IndexedWidgetBuilder (a function object) 我正在用多个构造函数实现一个类,该类在内部围绕IndexedWidgetBuilder(一个函数对象)构建
typedef IndexedWidgetBuilder = Widget Function(BuildContext context, int index);
Now, one of the constructors, call it MyWidget.list
shall receive a list myList
and create the IndexedWidgetBuilder myBuilder
from it: 现在,一个
MyWidget.list
的构造MyWidget.list
将收到一个列表myList
并myList
创建IndexedWidgetBuilder myBuilder
:
IndexedWidgetBuilder myBuilder
= (BuildContext context, int index) => list[index % list.length];
While this code snippet alone works perfectly, I am not able to use this inside the initializer list of the constructor. 虽然仅此代码段即可完美工作,但我无法在构造函数的初始化列表中使用此代码段。 A minimal working example reads
一个最小的工作示例如下
class MyApp {
// Default constructor goes here
MyApp.list(List<int> myList) :
myBuilder = (BuildContext context, int index) => list[index % list.length];
final IndexedWidgetBuilder myBuilder;
}
In Android studio, this snippet produces the error: 在Android Studio中,此代码段会产生错误:
The initializer type 'Type' can't be assigned to the field type '(BuildContext, int) → Widget'.
初始化类型'Type'不能分配给字段类型'(BuildContext,int)→Widget'。
I did not find anything related on google and the language documentation also did not provide useful information. 我没有在Google上找到任何相关信息,语言文档也未提供有用的信息。 Removing the
final
keyword and moving everything into the code block of the constructor would be a solution, albeit one I would only consider a last resort. 删除
final
关键字并将所有内容移到构造函数的代码块中将是一个解决方案,尽管我只考虑万不得已。
Note: This is not directly a flutter problem, since it occurs with every function objects. 注意:这不是直接的抖动问题,因为它发生在每个功能对象上。
Enclosing the function in parentheses seems to make the warning go away; 将函数括在括号中似乎可以消除警告。 though changes it to saying the parentheses are redundant!
虽然将其改为说括号是多余的!
MyApp.list(List<Widget> list)
: myBuilder =
((_, int index) => list[index % list.length]);
Notice how the context is unused. 注意上下文是如何未使用的。 That means that your pre-built widgets do not have access to it, which means they can't use it for any of the
.of()
derived uses. 这意味着您的预构建窗口小部件无法访问它,这意味着它们不能将其用于任何
.of()
派生用途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.