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 Patterns


Share

Dart Patterns

A pattern describes the shape of a value.

Dart can use a pattern in two ways:

  • To destructure a value, which means to unpack its parts into separate variables.
  • To match a value, which means to check if the value has a certain shape.

Patterns work with records, lists, maps and objects.

Note: Patterns were added in Dart 3, together with records.


Destructure a Record

In the Records chapter, we used $1 and $2 to get the fields of a record.

With a pattern, you can unpack all the fields into variables in one line:

Example

void main() {
  var car = ('Volvo', 2020);
  var (brand, year) = car;
  print('$brand, $year');

  var person = (name: 'Liam', age: 30);
  var (:name, :age) = person;
  print('$name is $age years old');
}
Try it Yourself »

Result:

Volvo, 2020
Liam is 30 years old

The pattern (brand, year) has the same shape as the record, so the first field goes into brand and the second field goes into year.

For named fields, the pattern :name gets the field name into a variable with the same name.

If you want a different variable name, write name: variable, like var (name: personName, age: personAge) = person;.

This is very useful when a function returns a record:

Example

(int, int) minMax(List<int> numbers) {
  var sorted = [...numbers]..sort();
  return (sorted.first, sorted.last);
}

void main() {
  var (low, high) = minMax([7, 2, 9, 4]);
  print('Lowest: $low');
  print('Highest: $high');
}
Try it Yourself »

Result:

Lowest: 2
Highest: 9


Destructure Lists and Maps

A list pattern is written with square brackets [].

It unpacks the items of a list in order:

Example

void main() {
  var scores = [90, 75, 60];
  var [first, second, third] = scores;
  print('$first, $second, $third');

  var fruits = ['Apple', 'Banana', 'Cherry', 'Mango'];
  var [favorite, ...others] = fruits;
  print(favorite);
  print(others);
}
Try it Yourself »

Result:

90, 75, 60
Apple
[Banana, Cherry, Mango]

Without ..., the list must have exactly as many items as the pattern.

The ...others part is called a rest element, and it collects the remaining items into a new list.

A map pattern is written with curly brackets {}, and gets the values of the keys you name.

Other keys in the map are ignored:

Example

void main() {
  var user = {'name': 'Emma', 'city': 'Oslo', 'age': 25};
  var {'name': name, 'city': city} = user;
  print('$name lives in $city');
}
Try it Yourself »

Result:

Emma lives in Oslo

The Wildcard _

Sometimes you only need some of the values.

Use the wildcard _ for a value you do not need.

The wildcard matches any value, but does not create a variable:

Example

void main() {
  var car = ('Volvo', 2020, 'red');
  var (brand, _, color) = car;
  print('$brand, $color');

  var [winner, _, _] = ['Anna', 'Liam', 'Emma'];
  print('Winner: $winner');
}
Try it Yourself »

Result:

Volvo, red
Winner: Anna

Match a Value with if-case

When you destructure a list with var, the list must have the right length, or the program stops with an error.

When you are not sure about the shape, use if with case.

The code in the if block only runs if the value matches the pattern:

Example

void main() {
  var point = [3, 5];
  if (point case [var x, var y]) {
    print('x is $x and y is $y');
  }

  var numbers = [1, 2, 3];
  if (numbers case [var a, var b]) {
    print('Two numbers');
  } else {
    print('Not two numbers');
  }
}
Try it Yourself »

Result:

x is 3 and y is 5
Not two numbers

Patterns like var x are called variable patterns, because they put the matched value into a new variable.

A variable pattern can also have a type, like String name.

Then it only matches values of that type.

This is a safe way to read data where you do not know the types, like a map from a file or a web server:

Example

void main() {
  Map<String, Object> data = {'name': 'Liam', 'age': 30};

  if (data case {'name': String name, 'age': int age}) {
    print('$name is $age years old');
  } else {
    print('Data is not valid');
  }

  Map<String, Object> bad = {'name': 'Liam', 'age': 'thirty'};

  if (bad case {'name': String name, 'age': int age}) {
    print('$name is $age years old');
  } else {
    print('Data is not valid');
  }
}
Try it Yourself »

Result:

Liam is 30 years old
Data is not valid

Patterns in for-in Loops

You can use a pattern in a for-in loop, to unpack each item as you go.

Here, each item in the list is a record:

Example

void main() {
  var scores = [('Anna', 90), ('Liam', 75), ('Emma', 82)];
  for (var (name, score) in scores) {
    print('$name: $score');
  }
}
Try it Yourself »

Result:

Anna: 90
Liam: 75
Emma: 82

Object Patterns

An object pattern matches an object of a class, and gets the values of its getters or fields.

You write the class name, and then the fields in parentheses.

Just like with named fields in records, :x gets the field x into a variable called x:

Example

class Point {
  final int x;
  final int y;
  Point(this.x, this.y);
}

void main() {
  var p = Point(3, 7);
  var Point(:x, :y) = p;
  print('x: $x, y: $y');
}
Try it Yourself »

Result:

x: 3, y: 7

Object patterns are often used in loops.

Each entry of a map is a MapEntry object with a key and a value:

Example

void main() {
  var prices = {'Apple': 1.5, 'Banana': 0.5, 'Cherry': 3.0};
  for (var MapEntry(:key, :value) in prices.entries) {
    print('$key costs $value');
  }
}
Try it Yourself »

Result:

Apple costs 1.5
Banana costs 0.5
Cherry costs 3.0

Tip: Patterns are even more powerful in switch expressions, which you will learn about in the next chapter.



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.