Is it possible to use multiple compute at the same time?
I'd like to call a heavy function on a list, which I want to run in parallel, but it crashes the app without any error message. Am I supposed to do only one compute call at a time?
Here's my test code that crashes often (but not always).
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: MyHomePage());
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<List<int>> f;
@override
void initState() {
super.initState();
f = getFutures();
}
Future<List<int>> getFutures() async {
List<int> output = [];
List<Future<int>> futures = [];
for (int i = 0; i < 100; ++i) {
print("call getFuture");
futures.add(getFuture());
}
for (int i = 0; i < futures.length; ++i) {
var f = await futures[i];
output.add(f);
}
return output;
}
Future<int> getFuture() async {
print("call compute");
var i = await compute(count, 1000000000);
return i;
}
static int count(int max) {
print("start count");
int j;
for (int i = 0; i < max; ++i) {
j = i;
}
return j;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("test")),
body: FutureBuilder<List<int>>(
future: f,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
print(snapshot);
return ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return Text("snapshot: ${snapshot.data[index]}");
});
break;
default:
return Center(child: CircularProgressIndicator());
}
}),
);
}
}