Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optional parameter in function definition and its usage syntax

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading