constructor - 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)
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:
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:
The initializer type 'Type' can't be assigned to the field type '(BuildContext, int) → Widget'.
I did not find anything related on google and the language documentation also did not provide useful information. 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.
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.
推荐阅读
- powershell - Powershell 访问被拒绝
- vba - 为什么每次循环都会出现类型不匹配?我不是在声明什么吗?
- arrays - 在 Ruby 语言的一个 if 语句中使用多个条件
- jquery - 为什么 JQuery 不改变 CSS 类?
- json - dart 中 json 映射的工厂和命名构造函数
- python - 你如何做一个嵌套循环,其中外循环的变量之一在内循环中运行?
- php - WooCommerce Checkout:根据付款方式设置字段(不)
- java - 编译 Android 项目时出现问题
- c# - 基于时间的进程杀死 VB.NET
- reverse-proxy - Minio 通过 Web 界面上传,API 收到“未经授权的请求”。