Open In App

Dart – Fat Arrow Notation

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:



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




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:




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:




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:




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:


Article Tags :