Thuta Learning
Dart
AdvancedProgrammingbeginner

Generics & Extension Methods

DartLesson 19

What you'll walk away with

  • Explain the type and runtime behavior of Generics & Extension Methods
  • Test null, failure, boundary, and async cases
  • Write safe, idiomatic, and testable Dart

Use Generics & Extension Methods to express stable APIs and exhaustive domain models. Prefer composition, sealed hierarchies, constrained generics, and focused extensions while minimizing hidden mutation and unchecked casts.

Build a Complete Mental Model

Use Generics & Extension Methods to express stable APIs and exhaustive domain models. Prefer composition, sealed hierarchies, constrained generics, and focused extensions while minimizing hidden mutation and unchecked casts.

Apply It in Modern Dart

Run and test an original Generics & Extension Methods example with null, empty, boundary, invalid, async-error, and cancellation cases. Use dart format, dart analyze, and dart test, and verify Future or Stream subscriptions and isolate boundaries where relevant.

After This Lesson

dart
T? firstOrNull<T>(List<T> values) => values.isEmpty ? null : values.first;

extension IntTotals on Iterable<int> {
  int get total => fold(0, (sum, value) => sum + value);
}

void main() {
  print(firstOrNull(<String>['Dart']));
  print([1, 2, 3].total);
}
You should see
Dart
6

Try It Yourself

Run and test an original Generics & Extension Methods example with null, empty, boundary, invalid, async-error, and cancellation cases. Use dart format, dart analyze, and dart test, and verify Future or Stream subscriptions and isolate boundaries where relevant.

Null and Async Warning

Assuming one sample output proves every null, promotion, Future, Stream, and isolate path.

Dart language overviewDart

Easy traps

  • Assuming one sample output proves every null, promotion, Future, Stream, and isolate path.
  • Bypassing type safety and resource lifecycles with dynamic, !, or an uncancelled Stream subscription.

Hands-on Exercise

Run and test an original Generics & Extension Methods example with null, empty, boundary, invalid, async-error, and cancellation cases. Use dart format, dart analyze, and dart test, and verify Future or Stream subscriptions and isolate boundaries where relevant.

You'll know it worked when: Dart 6