Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 213
manthano Avatar asked Feb 07 '19 21:02

manthano


1 Answers

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.

like image 104
Richard Heap Avatar answered Sep 18 '22 09:09

Richard Heap