Home > Software design >  Optional parameter in function definition and its usage syntax
Optional parameter in function definition and its usage syntax

Time:05-09

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)

CodePudding user response:

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))
  • Related