12

I have a function that should have three required and in best case named parameters. The last one ("finished") should be optional. I tried it like this:

static void showOverlay(BuildContext context, String text, bool successfull,
  [VoidCallback? finished]) {}

but Flutter is complaining:

Avoid positional boolean parameters

The weird thing is that it is only complaining about the bool successfull. What am I doing wrong here and how can I fix this?

1
  • @lrsvmb but right now the params are not named Commented Apr 22, 2021 at 11:46

3 Answers 3

12

Named parameters are optional by default. So in your case it would be:

static void showOverlay({BuildContext context, String text, bool successfull, VoidCallback? finished}) {}

Notice the {} in the constructor, this makes your parameters named and optional. By using @required in front of your declaration, you can differentiate between required and not required.

Sign up to request clarification or add additional context in comments.

1 Comment

For future reference, if you have enabled null-safety: @required is now just required
3

you can use it like this using positional parameters

 void showOverlay(BuildContext context, String text, bool successful, [VoidCallback finished]) {}

or like this using named parameters

void showOverlay({@required BuildContext context, @required String text, @required bool successful, VoidCallback finished}) {}

and dart is complaining becuase named parameters is best practice as mentioned in dart docs

Positional boolean parameters are a bad practice because they are very ambiguous. Using named boolean parameters is much more readable because it inherently describes what the boolean value represents.

BAD:

Task(true);
Task(false);
ListBox(false, true, true);
Button(false);

GOOD:

Task.oneShot();
Task.repeating();
ListBox(scroll: true, showScrollbars: true);
Button(ButtonState.enabled);

Comments

1

Named parameters are optional unless they’re specifically marked as required. Below, all four of your parameters are named. Three are required while one of them is optional.

static void showOverlay({required BuildContext context, required String text, 
  required bool successfull, VoidCallback? finished}) {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.