简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM