Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Generics


Share

Dart Generics

Generics let you write code that works with many types, but is still type-safe.

Type-safe means that Dart checks the types for you, and stops you if you use a wrong type.

You have already used generics with lists and maps.

The type inside the angle brackets <> is called a type argument:

Example

void main() {
  List<String> fruits = ['apple', 'banana'];
  Map<String, int> ages = {'John': 36, 'Anna': 28};

  fruits.add('cherry');
  ages['Linus'] = 41;

  print(fruits);
  print(ages);
}
Try it Yourself »

Result:

[apple, banana, cherry]
{John: 36, Anna: 28, Linus: 41}

List<String> is a list that can only hold strings.

If you try to add a number, you get an error:

Example

void main() {
  List<String> fruits = ['apple', 'banana'];
  fruits.add(42);
  print(fruits);
}
Try it Yourself »

Result:

main.dart:3:14: Error: The argument type 'int' can't be assigned to the parameter type 'String'.
  fruits.add(42);
             ^

You can also write the type argument on the value instead of the variable:

Example

void main() {
  var scores = <int>[];
  var prices = <String, double>{};

  scores.add(90);
  prices['milk'] = 1.25;

  print(scores);
  print(prices);
}
Try it Yourself »

Result:

[90]
{milk: 1.25}

Generic Classes

You can write your own generic class.

Put a type parameter in angle brackets after the class name.

By convention, the type parameter is a single capital letter, like T (for "type").

Inside the class, T stands for the real type that is used later:

Example

class Box<T> {
  T content;

  Box(this.content);

  T open() {
    return content;
  }
}

void main() {
  var stringBox = Box<String>('A gift');
  var intBox = Box<int>(100);

  print(stringBox.open());
  print(intBox.open());
}
Try it Yourself »

Result:

A gift
100

The same Box class works for strings, numbers and any other type.

A Box<int> can only hold an int:

Example

class Box<T> {
  T content;

  Box(this.content);
}

void main() {
  var intBox = Box<int>(100);
  intBox.content = 'hello';
  print(intBox.content);
}
Try it Yourself »

Result:

main.dart:9:20: Error: A value of type 'String' can't be assigned to a variable of type 'int'.
  intBox.content = 'hello';
                   ^

Tip: You can often leave out the type argument, and Dart works it out from the value.

Box('A gift') creates a Box<String>.



Several Type Parameters

A class can have more than one type parameter.

Separate them with commas, like in Map<K, V>:

Example

class Pair<A, B> {
  A first;
  B second;

  Pair(this.first, this.second);

  void show() {
    print('$first and $second');
  }
}

void main() {
  var p1 = Pair<String, int>('Apples', 5);
  var p2 = Pair<bool, double>(true, 3.14);

  p1.show();
  p2.show();
}
Try it Yourself »

Result:

Apples and 5
true and 3.14

Generic Functions

A function can also have a type parameter.

Write it in angle brackets after the function name:

Example

T firstItem<T>(List<T> items) {
  return items[0];
}

void main() {
  var names = ['Liam', 'Olivia', 'Noah'];
  var numbers = [7, 3, 9];

  String name = firstItem(names);
  int number = firstItem(numbers);

  print(name);
  print(number);
}
Try it Yourself »

Result:

Liam
7

The function returns a String for a list of strings, and an int for a list of integers.


Bounded Types

Sometimes a type parameter should only allow some types.

Use extends to set a limit, called a bound.

T extends num means that T must be num or a type of number, like int or double:

Example

T biggest<T extends num>(List<T> values) {
  var max = values[0];
  for (var value in values) {
    if (value > max) {
      max = value;
    }
  }
  return max;
}

void main() {
  print(biggest([4, 12, 7]));
  print(biggest([2.5, 1.5, 9.75]));
}
Try it Yourself »

Result:

12
9.75

Because T is always a number, the code can use > on the values.

If you use a type that is not a number, you get an error:

Example

T biggest<T extends num>(List<T> values) {
  var max = values[0];
  for (var value in values) {
    if (value > max) {
      max = value;
    }
  }
  return max;
}

void main() {
  print(biggest(['cat', 'dog']));
}
Try it Yourself »

Result:

main.dart:12:18: Error: A value of type 'String' can't be assigned to a variable of type 'num'.
  print(biggest(['cat', 'dog']));
                 ^
main.dart:12:25: Error: A value of type 'String' can't be assigned to a variable of type 'num'.
  print(biggest(['cat', 'dog']));
                        ^


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.