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 Extension Methods


Share

Dart Extension Methods

An extension method adds a new method to a type that already exists.

You can add methods to types that you did not write yourself, like String or int.

You do not need to change the original class, and you do not need a subclass.

You write an extension with the extension and on keywords:

extension ExtensionName on Type {
  // new methods and getters
}

Extension on String

This extension adds a shout() method to all strings:

Example

extension Shouting on String {
  String shout() {
    return '${toUpperCase()}!';
  }
}

void main() {
  print('hello'.shout());
  var name = 'dart';
  print(name.shout());
}
Try it Yourself »

Result:

HELLO!
DART!

Inside the extension, this is the string that the method is called on.

You can write this.toUpperCase() or just toUpperCase().

Extension methods can also have parameters:

Example

extension Repeat on String {
  String repeat(int times, String separator) {
    var parts = <String>[];
    for (var i = 0; i < times; i++) {
      parts.add(this);
    }
    return parts.join(separator);
  }
}

void main() {
  print('Hip'.repeat(3, ' '));
  print('ab'.repeat(4, '-'));
}
Try it Yourself »

Result:

Hip Hip Hip
ab-ab-ab-ab


Extension on int

You can extend numbers in the same way:

Example

extension NumberTools on int {
  int doubled() => this * 2;

  bool isBetween(int min, int max) {
    return this >= min && this <= max;
  }
}

void main() {
  print(5.doubled());
  print(15.isBetween(10, 20));

  var age = 8;
  print(age.isBetween(13, 19));
}
Try it Yourself »

Result:

10
true
false

Getters in Extensions

An extension can also add getters.

A getter is used without parentheses, just like a field:

Example

extension Scores on List<int> {
  int get total {
    var sum = 0;
    for (var score in this) {
      sum += score;
    }
    return sum;
  }

  double get average => total / length;
}

void main() {
  var scores = [80, 95, 70, 85];
  print(scores.total);
  print(scores.average);
}
Try it Yourself »

Result:

330
82.5

This extension works on List<int>, so it only works on lists of integers.

A list of strings does not get the total getter:

Example

extension Scores on List<int> {
  int get total {
    var sum = 0;
    for (var score in this) {
      sum += score;
    }
    return sum;
  }
}

void main() {
  var fruits = ['apple', 'banana'];
  print(fruits.total);
}
Try it Yourself »

Result:

main.dart:13:16: Error: The getter 'total' isn't defined for the type 'List<String>'.
 - 'List' is from 'dart:core'.
Try correcting the name to the name of an existing getter, or defining a getter or field named 'total'.
  print(fruits.total);
               ^^^^^

Named and Unnamed Extensions

All extensions on this page so far have a name, like Shouting or NumberTools.

The name is optional.

An extension without a name can only be used in the file where it is written:

Example

extension on String {
  bool get isLong => length > 5;
}

void main() {
  print('cat'.isLong);
  print('elephant'.isLong);
}
Try it Yourself »

Result:

false
true

A named extension can be used in other files that import it.

You can also use the name to call the extension directly.

This is useful when two extensions have a method with the same name:

Example

extension English on String {
  String greet() => 'Hello, $this';
}

extension Spanish on String {
  String greet() => 'Hola, $this';
}

void main() {
  print(English('Maria').greet());
  print(Spanish('Maria').greet());
}
Try it Yourself »

Result:

Hello, Maria
Hola, Maria

Note: An extension cannot add a field to an object.

It can only add methods, getters, setters and operators.



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.