CodeNewbie Community 🌱

Vishnubhotla Bharadwaj
Vishnubhotla Bharadwaj

Posted on • Originally published at bharadwaj.hashnode.dev on

Arrow syntax in Flutter

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;
}

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)