Sreejith N S
Sreejith N S

Reputation: 470

What's the meaning of “=>” (arrow) in Dart/Flutter?

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

What does this syntax (=>) mean?

_MyAppState createState() => _MyAppState();

Upvotes: 34

Views: 32812

Answers (1)

MendelG
MendelG

Reputation: 20038

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.

Upvotes: 65

Related Questions