26
  [
    Provider<FirebaseAuthService>(
      create: (_) => FirebaseAuthService(),
    ),
    Provider<ImagePickerService>(
      create: (_) => ImagePickerService(),
    ),
  ],

What does this syntax (=>) mean?

_MyAppState createState() => _MyAppState();
MendelG
  • 14,885
  • 4
  • 25
  • 52
Sreejith N S
  • 380
  • 1
  • 4
  • 11

1 Answers1

55

From the documentation:

For functions that contain just one expression, you can use a shorthand syntax. The => expr syntax is a shorthand for { return expr; }. The => notation is sometimes referred to as arrow syntax.

Note: Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an if statement there, but you can use a conditional expression.


Code example:

The following function:

int sum(int x, int y) {
  return x + y;
}

can be rewritten using the arrow function syntax as follows:

int sum(int x, int y) => x + y;

Additional example

String checkNumber(int x) => x > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";

is equivalent to:

String checkNumber(int x) {
  return x > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
}

Keep in mind that if your function is complex and requires multiple expressions or statements, you will need to use the traditional function declaration syntax with curly braces {}.


Additionally, if you select the actual arrow function (=>) in Android Studio and click on the yellow Bulb icon, you will have the option to "convert to block body":

enter image description here

And vice versa for converting from an arrow function to simply return.

MendelG
  • 14,885
  • 4
  • 25
  • 52
  • I have a question when we are using stateful object we usually have that notation for example? `State createState() => _CartPageState();`. I have tried to replace it with return but it didn't work. Does it mean it has a different meaning too? where `_CartPageState` is a class that extends `State` – Karue Benson Karue Jul 01 '23 at 01:20
  • @KarueBensonKarue I just tested and it works for me. Don't forget to add the `return` keyword within the `{}` – MendelG Aug 04 '23 at 01:29
  • Yeap it was my mistake it worked geeat too – Karue Benson Karue Aug 20 '23 at 17:38