Skip to content

Instantly share code, notes, and snippets.

@magicleon94
Last active July 9, 2020 12:13
Show Gist options
  • Save magicleon94/8ae4f73d42fe6c60c5f1f5c08fc20b39 to your computer and use it in GitHub Desktop.
Save magicleon94/8ae4f73d42fe6c60c5f1f5c08fc20b39 to your computer and use it in GitHub Desktop.
A simple helper to map states of a snapshot coming from a StreamBuilder
import 'package:flutter/material.dart';
typedef SnapshotBuilder<T> = Widget Function(AsyncSnapshot<T>);
class SnapshotHelper<T> {
final AsyncSnapshot<T> snapshot;
SnapshotHelper._(this.snapshot);
factory SnapshotHelper.of(AsyncSnapshot snapshot) =>
SnapshotHelper._(snapshot);
Widget getWidget(
{SnapshotBuilder<T> onData,
SnapshotBuilder<T> onError,
SnapshotBuilder<T> onLoading}) {
if (snapshot.hasError) {
return onError(snapshot);
} else if (snapshot.connectionState == ConnectionState.waiting) {
return onLoading(snapshot);
} else if (snapshot.connectionState == ConnectionState.active &&
!snapshot.hasData) {
return onLoading(snapshot);
} else if (snapshot.hasData && !snapshot.hasError) {
return onData(snapshot);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment