Flutter: Operator precedence

In Dart, like other programming languages when we have some arithmetic operations like addition, subtraction, multiplication, division, etc. The order in which the operations are evaluated is not from left to right.

Let's look at the following code fragment:

var result = 5 + 5 / 2;

If it is evaluated from left to right, the result will be 5, but the result is not 5. The result is 7.5. Why? Well, because the division has priority over the addition, 5/2 is evaluated first, then the result will be added to 5.

The following table contains the operator precedence in Dart. The items at the top have higher precedence.

Parenthesis( )
Multiplication, Division, Modulus* / ~/ %
Addition, Substraction+ -.

In the previous table, we can see that anything inside the parenthesis will be evaluated first. Then multiplications, divisions, and modulus operations. Finally, additions and subtractions at the end.

If we add a parenthesis to the previous code, we can see the result now is 5.

var result = ( 5 + 5 ) / 2;

Let's run the following examples in DartPad:

Share this article