Last active
February 13, 2020 08:30
-
-
Save rafa-js/ca0639680319827a33f432e0e521773e to your computer and use it in GitHub Desktop.
[Flutter] Reusable Widget to handle the common flows working with Streams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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