← Flutter / Dart

Flutter / Dart · 03 / 18

Operators and decisions with if

Compare values and execute instructions only when a condition matches.

  • Small
  • Basics
  • 15 min

Prerequisites: Variables, data types and missing values

Programs need to respond to different inputs. A comparison produces true or false. if uses that result to choose a path. We check mileage. A negative number can be stored as an int but is invalid under our domain rule. Types and domain rules therefore answer different questions.

Example files

01Read comparisons

== tests equality, != inequality, < less than and >= greater than or equal. In contrast, = is assignment. && requires both conditions to be true. || requires at least one true condition.

conditions.dart · dartOpen file
void main() {
  final mileage = 64920;
  if (mileage < 0) {
    print('Invalid mileage');
  } else if (mileage < 10000) {
    print('Low mileage');
  } else {
    print('Used vehicle');
  }
}

Run / check

dart run conditions.dart

02Choose branches

Dart checks conditions in order. It executes the first matching branch. else is the fallback if no previous condition matches. With 64920, our final branch is selected.

03Explore boundaries

Test -1, 0, 9999 and 10000. Boundary values help you understand the difference between < and <=. A later application checks the same rule in a service so it applies independently of the interface.

Expected result

With 64920: Used vehicle

Your exercise

Add a branch before the final else for values from 10000 up to, but excluding, 50000.

Show the solution and explanation

Use else if (mileage < 50000). Earlier branches have already handled negatives and values below 10000. An additional >= 10000 check is unnecessary here.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.