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.