Arrow syntax in Flutter

Subscribe to my newsletter and never miss my upcoming articles

There are many names for this Arrow syntax, some call it "Fat Arrow" and others argue it as "Shorthand syntax", also called "Expression in the function". Keeping all these names aside the main aim of using this is, it is used to define a single expression in a function.

The symbol convention is this "=>". (Somewhat like = >)

The normal syntax to write the code of adding two numbers in dart is as follows

void main()
{
print(add(20,20));
}
int add(int a, int b)
{
  int c = a+b;
  return c;
}

There are two important rules to be followed when one is using Fat Arrow :

  1. One needs to remove the return statement, as default it indicates return statement.

The above code can be modified like this

void main()
{
print(add(20,20));
}
int add(int a, int b) => a+b;

Two statements in the add function can be written as a single statement. On clear observation, we can see that curly braces ({}) are also removed. This leads to our second rule

  1. Curly braces should also be removed when one uses Fat Arrow.

So, The code can be further modified as

 void main() => print(add(10,20));
 int add(int a, int b) => a+b;

That's it. The summary of this is simply to use this syntax only when the function can be written in single expression.

No Comments Yet