1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
| import 'dart:async';
import 'dart:isolate';
import 'dart:math';
import 'dart:convert';
import 'package:flutter/foundation.dart'; // compute
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: _DemoPage()));
// ββ Models βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class User {
final int id;
final String name;
final String email;
User({required this.id, required this.name, required this.email});
factory User.fromJson(Map<String, dynamic> json) => User(
id: json['id'] as int,
name: json['name'] as String,
email: json['email'] as String,
);
}
// ββ Top-level functions (required for Isolate) βββββββββββββββββββββββββββββββββ
// Functions passed to compute/Isolate.spawn MUST be top-level or static
List<User> _parseUsers(String jsonStr) {
final List<dynamic> raw = jsonDecode(jsonStr) as List;
return raw.map((e) => User.fromJson(e as Map<String, dynamic>)).toList();
}
// Generates sample JSON with N users
String _generateUsersJson(int count) {
final rng = Random();
const names = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Frank', 'Grace'];
final list = List.generate(count, (i) => {
'id': i + 1,
'name': names[rng.nextInt(names.length)],
'email': 'user$i@example.com',
});
return jsonEncode(list);
}
// Function for the primes Isolate β receives SendPort to report progress
void _findPrimesIsolate(List<dynamic> args) {
final sendPort = args[0] as SendPort;
final limit = args[1] as int;
final primes = <int>[];
for (int n = 2; n <= limit; n++) {
bool isPrime = true;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) { isPrime = false; break; }
}
if (isPrime) primes.add(n);
// Report progress every 1000 numbers
if (n % 1000 == 0) {
sendPort.send({'progress': n / limit, 'count': primes.length});
}
}
// Final message with complete result
sendPort.send({'done': true, 'primes': primes.length, 'largest': primes.last});
}
// ββ Main screen ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class _DemoPage extends StatelessWidget {
const _DemoPage();
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: const Text('Isolates demo'),
bottom: const TabBar(tabs: [
Tab(text: 'compute'),
Tab(text: 'Isolate'),
Tab(text: 'Isolate.run'),
]),
),
body: const TabBarView(children: [
_ComputePage(),
_IsolatePage(),
_IsolateRunPage(),
]),
),
);
}
}
// ββ 1. compute β parsing 50,000 users βββββββββββββββββββββββββββββββββββββββββ
class _ComputePage extends StatefulWidget {
const _ComputePage();
@override
State<_ComputePage> createState() => _ComputePageState();
}
class _ComputePageState extends State<_ComputePage> {
String _status = 'Press the button to parse 50,000 users';
List<User>? _users;
bool _loading = false;
Future<void> _parse() async {
setState(() { _loading = true; _status = 'Generating JSONβ¦'; });
// Generate JSON on the main isolate (fast)
final json = _generateUsersJson(50000);
setState(() => _status = 'Parsing in a separate isolateβ¦');
final sw = Stopwatch()..start();
// compute sends the function + argument to a temporary isolate
// The main thread is NEVER blocked
final users = await compute(_parseUsers, json);
sw.stop();
setState(() {
_users = users;
_loading = false;
_status = 'β
${users.length} users in ${sw.elapsedMilliseconds} ms';
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_status, textAlign: TextAlign.center),
const SizedBox(height: 24),
if (_loading) const CircularProgressIndicator(),
if (!_loading)
FilledButton(onPressed: _parse, child: const Text('Parse JSON')),
if (_users != null) ...[
const SizedBox(height: 16),
Text('First 3: ${_users!.take(3).map((u) => u.name).join(', ')}'),
],
],
),
),
);
}
}
// ββ 2. Bidirectional Isolate with progress βββββββββββββββββββββββββββββββββββββ
class _IsolatePage extends StatefulWidget {
const _IsolatePage();
@override
State<_IsolatePage> createState() => _IsolatePageState();
}
class _IsolatePageState extends State<_IsolatePage> {
double _progress = 0;
String _status = 'Idle';
Isolate? _isolate;
bool _running = false;
Future<void> _start() async {
if (_running) return;
setState(() { _running = true; _progress = 0; _status = 'Calculatingβ¦'; });
final receivePort = ReceivePort();
_isolate = await Isolate.spawn(
_findPrimesIsolate,
[receivePort.sendPort, 100000], // find primes up to 100,000
);
receivePort.listen((message) {
final msg = message as Map<String, dynamic>;
if (mounted) {
if (msg.containsKey('done')) {
setState(() {
_running = false;
_progress = 1;
_status = 'β
${msg['primes']} primes. Largest: ${msg['largest']}';
});
receivePort.close();
} else {
setState(() {
_progress = msg['progress'] as double;
_status = 'Primes found: ${msg['count']}';
});
}
}
});
}
void _cancel() {
_isolate?.kill(priority: Isolate.immediate);
setState(() { _running = false; _status = 'Cancelled'; _progress = 0; });
}
@override
void dispose() {
_isolate?.kill(priority: Isolate.immediate);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_status, textAlign: TextAlign.center),
const SizedBox(height: 16),
LinearProgressIndicator(value: _progress),
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FilledButton(
onPressed: _running ? null : _start,
child: const Text('Calculate primes')),
const SizedBox(width: 12),
OutlinedButton(
onPressed: _running ? _cancel : null,
child: const Text('Cancel')),
],
),
],
),
),
);
}
}
// ββ 3. Isolate.run β Flutter 3.7+ βββββββββββββββββββββββββββββββββββββββββββββ
class _IsolateRunPage extends StatefulWidget {
const _IsolateRunPage();
@override
State<_IsolateRunPage> createState() => _IsolateRunPageState();
}
class _IsolateRunPageState extends State<_IsolateRunPage> {
String _result = 'Press to compute a hash of 1 MB of data';
bool _loading = false;
Future<void> _run() async {
setState(() { _loading = true; _result = 'Calculatingβ¦'; });
// Isolate.run: creates an isolate, runs the function, destroys it when done
// Simpler than Isolate.spawn for one-shot tasks with no progress
final result = await Isolate.run(() {
// Simulate heavy work: compute hash over a million iterations
var hash = 0;
for (int i = 0; i < 1000000; i++) {
hash = (hash + i * 31) & 0xFFFFFFFF;
}
return 'Simulated hash: 0x${hash.toRadixString(16).padLeft(8, '0').toUpperCase()}';
});
setState(() { _loading = false; _result = result; });
}
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_result, textAlign: TextAlign.center),
const SizedBox(height: 24),
if (_loading) const CircularProgressIndicator(),
if (!_loading)
FilledButton(onPressed: _run, child: const Text('Run in Isolate')),
],
),
),
);
}
}
|