In my Project I have a heavy async task which is executed in a secondary Isolate.
I want to display the progress of this task to the UI with a ProgressIndicator()
.
I tried using a callback function passed to the Isolate as a parameter, but this did not work.
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
class IsolateProgress extends StatelessWidget {
const IsolateProgress({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Isolate Progress')),
body: FutureBuilder(
future: compute(_heavyTask, [1, 11, 111, 1111, 11111, 96953, 111111, 99971, 11111111, 999999487]),
builder: (context, AsyncSnapshot<Map<int, bool>> snapshot) {
if (snapshot.hasData) {
return ListView(
children: snapshot.data!.entries.map((e) => Text('${e.key}: ${e.value ? 'prime' : 'no prime'}')).toList(),
);
}
return Center(
child: CircularProgressIndicator(
// value: x (from Isolate),
),
);
},
),
);
}
Future<Map<int, bool>> _heavyTask(List<int> listToCheck) async {
Map<int, bool> result = {};
for (int num in listToCheck) {
// async call on each loop
await Future.delayed(Duration(milliseconds: 100));
if (num == 1) {
result[1] = false;
}
result[num] = true;
for (int i = 2; i < num; ++i) {
if (num % i == 0) {
result[num] = false;
}
}
// here: somehow send a message to main Isolate to add a step to CircularProgressIndicator()
}
return result;
}
}
2
Answers
I’m working on how to return Stream from Isolate.
But is this what you need?(Async version)
(Isolate version)
You need to create ReceivePort and sendPort to communicate between different Isolate.