Dart Fat Arrow => or ShortHand Syntax Tutorial

5
16739
fat arrow in Dart
Dart fat arrow or shorthand syntax

In this tutorial, we are going to learn something unique than other programming languages. This tutorial is all about Dart fat arrow => or shorthand syntax. Short hand expression is used to define a single expression in a function. Enough with the definition and properties.

The syntax of fat arrow or shorthand syntax expression looks like this.

  
ReturnType FunctionName(Parameters...) => Expression;
  • By using fat arrow => the curly brackets needs to be removed. Otherwise, the code editor will show you an error.
  • If a function has a return type then by using a Fat arrow it is required to remove the return keyword.

Let me show you side by side. Both are the same function and will return the same value. Just a different syntax

  
var size = (int s) => s*2;
  
var size = (int s) { 
return s*2; } 

To understand the concept with a real code example. We will consider the same examples that are done in Dart functions tutorial. The code executes the Perimeter and Area of a rectangle. This is how usually it is done with the help of functions.

  
 void main() {
  findPerimeter(9, 6);
  var rectArea = findArea(10, 6);
  print('The area is $rectArea');
}

void findPerimeter(int length, int breadth) {
  var perimeter = 2 * (length * breadth);
  print('The perimeter is $perimeter');
}

int findArea(int length, int breadth) {
  return length * breadth;
}

The given functions can be optimized with the help of fat arrow in Dart.

  
 void main() {
  findPerimeter(9, 6);
  var rectArea = findArea(10, 6);
  print('The area is $rectArea');
}

void findPerimeter(int length, int breadth) =>
  print('The perimeter is ${2 * (length * breadth)}');


int findArea(int length, int breadth) =>
   length * breadth;

After hitting the run button we are still getting the same result.

  
 The perimeter is 108
The area is 60

Please pay special focus on findArea function. By using fat arrow, return keyword is need to be removed.

5 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here