flutterfunctionargumentsoption-typenamed

flutter mix optional and named arguments in a function


I have a simple problem but I cannot find an answer to my question.

Is there a way to mix : optional arguments with default value and required named arguments in a flutter function ?

I need something like that but this exemple doesn't works in flutter.

 Future<void> getNationalRanking({required String connectedUserId}, [countryCode = "FR"]) async {
// blabla 
}

it might be a stupid syntax that I don't know.

Thanks for your help


Solution

  • Named parameters are already optional if you don't make them required and either make them nullable or provide a default value. For example:

    Future<void> getNationalRanking({
      required String connectedUserId,
      String? countryCode,
    }) async {
      countryCode ??= "FR";
      ...
    }
    

    or:

    Future<void> getNationalRanking({
      required String connectedUserId,
      String countryCode = "FR",
    }) async {
      ...
    }
    

    Your example attempts to mix named parameters with optional positional parameters, but using both is not allowed. From the Dart Language Tour:

    A function can have any number of required positional parameters. These can be followed either by named parameters or by optional positional parameters (but not both).

    Also see https://github.com/dart-lang/language/issues/1076.