Skip to content

Instantly share code, notes, and snippets.

@rafa-js
Last active February 13, 2020 08:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rafa-js/ca0639680319827a33f432e0e521773e to your computer and use it in GitHub Desktop.
Save rafa-js/ca0639680319827a33f432e0e521773e to your computer and use it in GitHub Desktop.
[Flutter] Reusable Widget to handle the common flows working with Streams
import 'package:flutter/material.dart';
class StreamWidget<T> extends StatelessWidget {
final Stream<T> stream;
final Widget Function() onLoading;
final Widget Function(T) onData;
final Widget Function(dynamic) onError;
const StreamWidget({
@required this.stream,
@required this.onData,
this.onError,
this.onLoading,
});
@override
Widget build(BuildContext context) {
return StreamBuilder<T>(
stream: stream,
builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
if (snapshot.hasData) {
return this._handleData(snapshot.data);
} else if (snapshot.hasError) {
return this._handleError(snapshot.error);
} else {
return this._handleLoading();
}
},
);
}
Widget _handleData(T data) {
return this.onData(data);
}
Widget _handleError(dynamic error) {
return this.onError != null ? this.onError(error) : Container();
}
Widget _handleLoading() {
return this.onLoading != null ? this.onLoading() : Container();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment