Optional parameter in function definition and its usage syntax

Issue

Here I have defined a method definition with optional named parameter.

class PostBuilder extends StatefulWidget {
  final Future<List<Submission>> Function({String? next}) postFetcher;
  ...
  ...
}

I can able to invoke that function as expected like below.

class _PostBuilderState extends State<PostBuilder> {
   ...
   ...
   
   _fetch() async {
     var posts = await widget.postFetcher();
     // or
     var posts = await widget.postFetcher(next: _items.getLast()?.name);
   }

But unfortunately, I cannot figure our how to use it properly and don’t know the correct syntax.

PostBuilder((next) => getPosts(next))

This is syntax error that is being thrown by the compiler

error: The argument type 'Future<List<Submission>> Function(dynamic)' can't be assigned to the parameter type 'Future<List<Submission>> Function({String? next})'. (argument_type_not_assignable)

Solution

postFetcher takes a named parameter. If you want to assign an anonymous function to it, that anonymous function also must take a named parameter. The syntax for anonymous functions is the same as for named functions (the types for anonymous functions are usually omitted because they can be inferred). You therefore want:

PostBuilder(({next}) => getPosts(next))

Answered By – jamesdlin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published