Skip to content

Instantly share code, notes, and snippets.

@micedreams
Created July 13, 2024 15:11
Show Gist options
  • Save micedreams/18bacf73b5badbcfbe1767d2bccd1af5 to your computer and use it in GitHub Desktop.
Save micedreams/18bacf73b5badbcfbe1767d2bccd1af5 to your computer and use it in GitHub Desktop.
Multi future
import 'package:flutter/widgets.dart';
import 'multi_future_listener.dart';
class MultiFutureBuilder<T> extends StatefulWidget {
final List<Future<T>> futures;
final Widget Function(BuildContext context, AsyncSnapshot<List<T>> snapshot)
builder;
const MultiFutureBuilder({
super.key,
required this.futures,
required this.builder,
});
@override
State createState() => _MultiFutureBuilderState<T>();
}
class _MultiFutureBuilderState<T> extends State<MultiFutureBuilder<T>> {
late List<Future<T>> _futures;
late AsyncSnapshot<List<T>> _snapshot;
@override
void initState() {
super.initState();
_futures = widget.futures;
// Initialize snapshot
_snapshot = AsyncSnapshot<List<T>>.withData(ConnectionState.none, []);
// Listen to the futures
MultiFutureListener(
futures: _futures,
onComplete: (results) {
setState(() {
_snapshot = AsyncSnapshot.withData(ConnectionState.done, results);
});
},
onError: (error) {
setState(() {
_snapshot = AsyncSnapshot.withError(ConnectionState.done, error);
});
},
);
}
@override
Widget build(BuildContext context) => widget.builder(context, _snapshot);
}
class MultiFutureListener<T> {
final List<Future<T>> futures;
final void Function(List<T> results) onComplete;
final void Function(Object error)? onError;
MultiFutureListener({
required this.futures,
required this.onComplete,
this.onError,
}) {
List<T> results = List.filled(futures.length, null as T);
int completedCount = 0;
futures.asMap().forEach((index, future) {
future.then((result) {
results[index] = result;
completedCount++;
if (completedCount == futures.length) {
onComplete(results);
}
}).catchError((error) {
if (onError != null) {
onError!(error);
}
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment