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 Isolates


Share

Dart Isolates

In the Async Intro chapter, you learned that Dart runs your code on one thread.

Futures are great for waiting, for example for a timer or a file.

But some tasks are not waiting, they are working hard, like doing a big calculation or reading a very large text.

A big calculation keeps the thread busy, and nothing else can run until it is done.

In an app, this makes the screen freeze.

An isolate solves this problem.

What Is an Isolate?

An isolate is a separate worker that runs Dart code next to your main program.

Every Dart program already runs in one isolate, called the main isolate.

You can start more isolates to do heavy work at the same time.

Each isolate has its own memory, so isolates do not share variables.

That is why it is called an isolate: it is isolated (kept apart) from the others.

The only way to share data is to send a message, for example the result of the work.


Isolate.run()

The easiest way to use an isolate is Isolate.run() from the dart:isolate library.

It does three things for you:

  1. It starts a new isolate.
  2. It runs your function in that isolate.
  3. It sends the result back as a future, and closes the isolate.

This example adds all the numbers from 1 to 100 million in a new isolate:

Example

import 'dart:isolate';

int sumNumbers() {
  int sum = 0;
  for (int i = 1; i <= 100000000; i++) {
    sum += i;
  }
  return sum;
}

Future<void> main() async {
  print('Starting the heavy work...');
  int result = await Isolate.run(sumNumbers);
  print('The sum is $result');
}
Try it Yourself »

Result:

Starting the heavy work...
The sum is 5000000050000000

Since Isolate.run() returns a future, you use await to get the result.



The Main Program Keeps Running

While the isolate is working, the main isolate is free to do other things.

Timer.periodic() from dart:async runs a function again and again, with a waiting time between each run.

In this example, a timer adds 1 to ticks every 100 milliseconds, while the heavy work runs in another isolate:

Example

import 'dart:async';
import 'dart:isolate';

int countPrimes(int max) {
  int count = 0;
  for (int n = 2; n <= max; n++) {
    bool isPrime = true;
    for (int d = 2; d * d <= n; d++) {
      if (n % d == 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) count++;
  }
  return count;
}

Future<void> main() async {
  int ticks = 0;
  final timer = Timer.periodic(Duration(milliseconds: 100), (t) {
    ticks++;
  });

  int primes = await Isolate.run(() => countPrimes(5000000));
  timer.cancel();

  print('Primes up to 5 million: $primes');
  print('Did the timer run? ${ticks > 0}');
}
Try it Yourself »

Result:

Primes up to 5 million: 348513
Did the timer run? true

The timer could keep counting, because the main isolate was not busy.

Now look at the same program without an isolate.

The calculation runs in the main isolate, so the timer cannot run at all until the calculation is done:

Example

import 'dart:async';

int countPrimes(int max) {
  int count = 0;
  for (int n = 2; n <= max; n++) {
    bool isPrime = true;
    for (int d = 2; d * d <= n; d++) {
      if (n % d == 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) count++;
  }
  return count;
}

void main() {
  int ticks = 0;
  final timer = Timer.periodic(Duration(milliseconds: 100), (t) {
    ticks++;
  });

  int primes = countPrimes(5000000);
  timer.cancel();

  print('Primes up to 5 million: $primes');
  print('Did the timer run? ${ticks > 0}');
}
Try it Yourself »

Result:

Primes up to 5 million: 348513
Did the timer run? false

Send Values to the Isolate

To give values to the function, wrap the call in an anonymous function, like () => countWords(text).

The values are copied into the new isolate:

Example

import 'dart:isolate';

int countWords(String text) {
  return text.split(' ').length;
}

Future<void> main() async {
  String story = 'Once upon a time there was a little cat';
  int words = await Isolate.run(() => countWords(story));
  print('The story has $words words');
}
Try it Yourself »

Result:

The story has 9 words

Isolates Do Not Share Memory

When an isolate changes a variable, it only changes its own copy.

The main isolate does not see the change:

Example

import 'dart:isolate';

int visitors = 0;

Future<void> main() async {
  int inside = await Isolate.run(() {
    visitors += 10;
    return visitors;
  });
  print('Visitors in the new isolate: $inside');
  print('Visitors in the main isolate: $visitors');
}
Try it Yourself »

Result:

Visitors in the new isolate: 10
Visitors in the main isolate: 0

To get data back from an isolate, return it from the function.


When to Use an Isolate

Most programs do not need isolates.

  • Use async and await when your program is waiting for something, like a timer, a file or the internet.
  • Use an isolate when your program is working hard on a long calculation.

Starting an isolate also takes a little time, so use it only for work that takes a long time.

Note: Isolate.run() does not work in Dart programs that run in a web browser.



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.