Isolate.spawn
- Dart course
- Advanced
- Lesson 2/83
- 5 min
Learn new isolates with Isolate.spawn.
Isolate.spawn signature
Isolate.spawn schedules a new isolate and returns Future<void>. The future completes when the isolate has been started — it does not wait for the work to finish.
The first parameter is the entryPoint of type void Function(List<String>). The second is a List<String> message list; typically the first element is a SendPort.
Example: await Isolate.spawn(worker, ['data']);. With await you wait for the isolate to be started; without it the main isolate continues immediately.
Passing data with spawn
The list passed as the second argument to spawn is copied into the isolate. Each element must be serializable (primitive, SendPort, List, Map).
A common pattern is to make the first element a SendPort: Isolate.spawn(worker, [port.sendPort, 'gorev-1']). The isolate then sends its result back through this port.
Note: closure variables cannot be passed. entryPoint can only read the parameter list.
Practice Get a single result with Isolate.run
Make main async. Add var result = await Isolate.run(() => 6 * 7); and print it with print(result);.
Starter code
import 'dart:isolate';
void main() {
// make async and compute 6*7 via Isolate.run
}Sample solution
import 'dart:isolate';
void main() async {
var result = await Isolate.run(() => 6 * 7);
print(result);
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 spawn return type
Future<____> IsolateSpawnFunction() => Isolate.spawn(entry, args);
Future<void> IsolateSpawnFunction() => Isolate.spawn(entry, args);
Explanation: Isolate.spawn returns Future<void>.
2 What is the return type of Isolate.spawn?
- void
- Future<void> Correct answer
- Stream<void>
- Isolate
Explanation: spawn returns Future<void> — it completes when the isolate has started.
3 Match the spawn parts
| Term | Meaning |
|---|---|
Future<void> |
spawn return type |
entryPoint |
Function to run |
List<String> |
Message list |
SendPort |
Reply channel |