← Flutter / Dart

Flutter / Dart · 02 / 18

Variables, data types and missing values

Store values under names and distinguish text, numbers and booleans.

  • Small
  • Basics
  • 15 min

Prerequisites: Install Dart and run your first program

A variable associates a name with a value so you can reuse it instead of typing it repeatedly. A data type describes which values are allowed. In Vehicle File, a name is text, mileage is a number and an enabled reminder is a yes/no decision. A missing value differs from the number zero.

Example files

01Declare values

String means text, int a whole number, double a number with a fractional part and bool true or false. The = operator assigns a value. Code uses a decimal point even if your interface later displays a comma.

values.dart · dartOpen file
void main() {
  final String name = 'Family car';
  int mileage = 64820;
  double litres = 42.5;
  bool reminder = true;
  String? plate;
  mileage += 100;
  print('$name: $mileage km, plate: ${plate ?? 'unknown'}');
  print('$litres litres, reminder: $reminder');
}

Run / check

dart run values.dart

02Change or fix a value

mileage += 100 increases the existing value by 100. final prevents later reassignment. With var, Dart infers the type from the first value. var does not permit storing arbitrary different types later.

03Represent missing information

String? permits text or null. The question mark belongs to the type. ?? chooses a fallback when the left side is null. An optional registration plate can therefore be absent without storing invented text.

Expected result

Output: Family car: 64920 km, plate: unknown

Your exercise

Create a costCents variable containing 12990. Print the amount in euros. Why is int useful for stored cents?

Show the solution and explanation

int costCents = 12990 stores the exact amount in cents. print(costCents / 100) shows 129.9. An interface can later format it as €129.90. Integer cents avoid floating-point rounding errors when storing money.

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.