CodeBlanks Logo Icon CodeBlanks

Generics vs dynamic

Learn the difference between generics and dynamic.

Generics vs dynamic

Generics fix the type at compile time; dynamic leaves the type to runtime. Both give flexibility but the safety level differs.

When you declare List<int>, the compiler knows the list holds only int; list.add('a') is a compile error. When you declare List<dynamic>, any type can be added; the error surfaces only at runtime, when the value is accessed. Generics catch the error early; dynamic is flexible but risky. For maintainable code, generics are preferred.

When to use which?

Generics are the default choice for collections and helper methods; they give type safety and readability. Declarations like List<int> and Map<String, int> surface errors at compile time.

dynamic is for cases where the type is not known up front: external data sources, reflection or temporary prototype code. But in production code dynamic should be a last resort. Generics give a contract to the compiler and the reader; dynamic removes that contract. The right choice is generics, which keeps safety.

Practice Write a generic pick<T> method

Define a generic method named T pick<T>(List<T> items, int i); its body should be return items[i];. In main, call print(pick<int>([1, 2, 3], 1));.

Starter code

main.dart
// Define the pick<T> method

void main() {
  // Call pick<int>([1, 2, 3], 1) and print
}

Sample solution

main.dart
// Define the pick<T> method
T pick<T>(List<T> items, int i) {
  return items[i];
}

void main() {
  print(pick<int>([1, 2, 3], 1));
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match generics and dynamic properties

Term Meaning
Generic Compile-time safety
dynamic Runtime check
List<int> Fixed type

2 Build a type-safe list

Question
var ages = <____>[28, 30];
print(ages[0]);
Answer
var ages = <int>[28, 30];
print(ages[0]);

Explanation: <int>[28, 30] produces a type-safe List<int>.

3 Which is the safest choice?

  • List<dynamic>
  • List<int> Correct answer
  • dynamic x
  • var x = 5

Explanation: List<int> fixes the type at compile time; it is the safest choice.

All lessons in Intermediate