Flutterで複数の非同期処理を実行する際のパターンをまとめました。
Future<String> asynchronous(String param) async {
return '戻り値: $param';
}
ひとつずつ直列で実行
Future<void> example1({required List<String> parameters}) async {
for (final String param in parameters) {
await asynchronous(param);
}
}
一気に並列で実行
Future<void> example3({required List<String> parameters}) async {
final List<Future<bool>> futures = <Future<bool>>[];
Future<bool> f(String param) async {
await asynchronous(param);
return true;
}
for (final String param in parameters) {
futures.add(f(param));
}
await Future.wait(futures);
}
複数まとめて並列で実行
Future<void> example2({required List<String> parameters}) async {
const int threadNum = 3;
List<Future<bool>> futures = <Future<bool>>[];
Future<bool> f(String param) async {
await asynchronous(param);
return true;
}
for (final List<String> subParams in partition(parameters, threadNum).toList()) {
futures = subParams.map((String param) => f(param)).toList();
await Future.wait(futures);
}
}
同時実行できる数を制限して順次実行
Future<void> example4({required List<String> parameters}) async {
const int threadNum = 3;
int currentIndex = 0;
final List<Future<bool>> futures = <Future<bool>>[];
Future<bool> f() async {
while (currentIndex < parameters.length) {
final String param = parameters[currentIndex];
currentIndex++;
await asynchronous(param);
}
return true;
}
for (int threadIndex = 0; threadIndex < threadNum; threadIndex++) {
futures.add(f());
}
Future.wait(futures);
}