DartIntermediate 2 min read

Dart generics and type bounds: build a typed page result

Preserve item types across reusable containers and constrain a type only when the API needs it.

On this page

A paginated response has the same outer structure for invoices, products and tasks. A generic container reuses that structure while preserving the type of each item. Callers should not need to cast every element back from dynamic.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
class Page<T> {
  Page(Iterable<T> items, {required this.hasMore})
      : items = List.unmodifiable(items);
  final List<T> items;
  final bool hasMore;
}

T larger<T extends num>(T first, T second) => first >= second ? first : second;

void main() {
  final page = Page<String>(['Invoice A', 'Invoice B'], hasMore: true);
  print(page.items.first.toUpperCase());
  print(larger<int>(4, 7));
}

Follow the data and control flow

The type argument flows into the items field, so the caller can use String operations without a cast. The constructor copies to an unmodifiable list, protecting the page’s list structure from later caller mutations.

The bound on larger makes numeric comparison available while preserving a numeric subtype. A generic parameter is meaningful when the relationship between input and output types matters. If every supported value only needs one interface, accepting that interface directly may be simpler.

A mistake to avoid

Replacing a precise generic with dynamic can defer a wrong item type until runtime. Variance also matters when exposing mutable generic collections: do not assume a list accepting one subtype can safely accept every supertype value. Keep public mutation contracts narrow.

Practice and verification

Create a page of task records and verify the record fields stay typed. Try an incompatible item intentionally and read the analyzer error. Add a generic map operation returning a new Page of another type without mutating the original.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.