Open In App

Dart – Fat Arrow Notation

Last Updated : 07 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In Dart, we have fat arrow notation ( => ).  A fat arrow is used to define a single expression in a function. This is a cleaner way to write functions with a single statement.

Declaring Fat arrow expression in dart –

Syntax :

ReturnType FunctionName(Parameters...) => Expression;

In the above syntax:

  • ReturnType consists of datatypes like void,int,bool, etc..
  • FunctionName defines the name of the function.
  • Parameters are the list of parameters function requires.

Let’s see how we can write the below code in a more short way.

Dart




void main() {
    
  perimeterOfRectangle(47, 57);
   
}
 
void perimeterOfRectangle(int length, int breadth) {
  var perimeter = 2 * (length + breadth);
  print('The perimeter of rectangle is $perimeter');
}


Output:

The perimeter of rectangle is 208

When the body of the function contains only one line, you can omit the curly braces and the return statement in favor of the “arrow syntax” as shown below:

Dart




void main() {
  perimeterOfRectangle(47, 57);
 }
 
// Arrow Syntax
void perimeterOfRectangle(int length, int breadth) =>
  print('The perimeter of rectangele is ${2 * (length + breadth)}');


Output:

The perimeter of rectangele is 208

If we compare the above code we got the same output with much less code using Fat arrow notation.

Example 1:

Consider the below code:

Dart




void sum (int x, int y) {
   
  // printing the result
  print( 'sum is ${x + y}');
}
 
void main (){
  sum(5,2);
}


Output:

sum is 7

The given functions can be optimized with the help of a fat arrow in Dart and the same output we can get:

Dart




void main(){
  sum(2,5);
}
 
// Arrow Syntax
void sum(int x,int y) => print('sum is ${ x + y}');


Output:

sum is 7

Points to remember:

  • Fat arrow is a clean way to write function expression in a single line.
  • Fat arrow notation doesn’t have statements body ‘ { } ‘ .
  • The statement body is replaced with   ‘ => ‘ fat arrow which points to a single statement.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads