Skip to content

Instantly share code, notes, and snippets.

@MariaMelnik
Created August 11, 2020 15:51
Show Gist options
  • Save MariaMelnik/c66b3edb5962cd50f8bb34ef0da72350 to your computer and use it in GitHub Desktop.
Save MariaMelnik/c66b3edb5962cd50f8bb34ef0da72350 to your computer and use it in GitHub Desktop.
import 'package:flutter/widgets.dart';
import 'new_sb_base.dart';
class MyStreamBuilder<T> extends MyStreamBuilderBase<T, AsyncSnapshot<T>> {
/// Creates a new [MyStreamBuilder] that builds itself based on the latest
/// snapshot of interaction with the specified [stream] and whose build
/// strategy is given by [builder].
///
/// The [initialData] is used to create the initial snapshot.
///
/// The [builder] must not be null.
const MyStreamBuilder({
Key key,
this.initialData,
Stream<T> stream,
@required this.builder,
}) : assert(builder != null),
super(key: key, stream: stream);
/// The build strategy currently used by this builder.
///
/// This builder must only return a widget and should not have any side
/// effects as it may be called multiple times.
final AsyncWidgetBuilder<T> builder;
/// The data that will be used to create the initial snapshot.
///
/// Providing this value (presumably obtained synchronously somehow when the
/// [Stream] was created) ensures that the first frame will show useful data.
/// Otherwise, the first frame will be built with the value null, regardless
/// of whether a value is available on the stream: since streams are
/// asynchronous, no events from the stream can be obtained before the initial
/// build.
final T initialData;
@override
AsyncSnapshot<T> initial() => AsyncSnapshot<T>.withData(ConnectionState.none, initialData);
@override
AsyncSnapshot<T> afterConnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.waiting);
@override
AsyncSnapshot<T> afterData(AsyncSnapshot<T> current, T data) {
return AsyncSnapshot<T>.withData(ConnectionState.active, data);
}
@override
AsyncSnapshot<T> afterError(AsyncSnapshot<T> current, Object error) {
return AsyncSnapshot<T>.withError(ConnectionState.active, error);
}
@override
AsyncSnapshot<T> afterDone(AsyncSnapshot<T> current) => current.inState(ConnectionState.done);
@override
AsyncSnapshot<T> afterDisconnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.none);
@override
Widget build(BuildContext context, AsyncSnapshot<T> currentSummary) => builder(context, currentSummary);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment