Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Forked from rafa-js/stream_widget.dart
Created February 13, 2020 08:29
Show Gist options
  • Save rodydavis/433d7f5e83c1a0e2585c9fde9f530865 to your computer and use it in GitHub Desktop.
Save rodydavis/433d7f5e83c1a0e2585c9fde9f530865 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