01 · Start well

Dart values types and null safety

Lesson 2 · 90 minutes including practice. Read, run the example, complete the task, then compare your work with the solution.

By the end of this lesson

  • Choose appropriate types for domain values.
  • Distinguish final, const and nullable values.
  • Validate input without hiding invalid data.

Model the meaning of a value

A variable has both a value and a type. Use a String for a product name, an int for a count and a bool for an explicit yes/no state. Avoid storing everything as text and converting repeatedly across the interface. In this course, money is represented as integer minor units, so KSh 125.50 becomes 12550. That keeps simple addition exact and avoids binary floating-point surprises.

Final does not freeze a whole object

Use final when a variable will not be reassigned. A final list can still be modified; the binding is fixed, not necessarily the object. Use immutable data structures or unmodifiable copies when callers must not alter a collection. A const value must be known at compile time; user input cannot be const.

Null means a missing value

A String cannot hold null unless its type is String?. A missing value and an empty string are different states: a missing phone number may be unknown, while an empty one may be supplied but invalid. Prefer checking and promoting a nullable value over using !. The assertion operator asks the runtime to trust you and can fail if your assumption is wrong.

Parsing is a boundary

Use int.tryParse where text enters your application. Decide what invalid input means before using a default. Turning every invalid quantity into zero can hide an error. A safe form returns a message and preserves the typed input so the user can correct it. Later, the same principle will be applied to JSON and database rows.

Worked example

The example below is a runnable Dart file; save it as example.dart and run dart run example.dart.

// standalone
int? parseQuantity(String raw) {
  final value = int.tryParse(raw.trim());
  if (value == null || value < 0) return null;
  return value;
}
void main() {
  final quantity = parseQuantity(' 12 ');
  if (quantity == null) {
    print('Enter a non-negative whole number.');
    return;
  }
  const unitPriceMinor = 12550;
  print('Quantity: $quantity');
  print('Total minor units: ${quantity * unitPriceMinor}');
}

Your practical task

Predict the results for "12", "-1", "", and "2.5" before running them. Extend the parser to reject quantities above 10,000. Explain why a negative amount is rejected rather than converted to positive.

Worked solution and reasoning — attempt the task first

Return null if the parsed value is null, below zero or above 10000. The valid sample produces 150600 minor units. The other three samples are invalid whole quantities. Using abs() would change the user's intention and could quietly turn a stock decrease into an increase. Validation should report a problem rather than invent a replacement.

Check your understanding

Is final List<int> the same as an immutable list?

No. The variable cannot be reassigned, but add() may still change its contents.

When is ?? appropriate?

When the fallback has an agreed meaning. A missing optional label may fall back to a display label; an invalid transaction amount should not silently become zero.

Official reference

Read the relevant official documentation. The reference extends this lesson; the exercise and explanation above are original course material.