Last active
July 19, 2019 10:46
-
-
Save DFelten/c00529f9641c738126d1360e692f21e0 to your computer and use it in GitHub Desktop.
Custom Stream Builder for Flutter BLoCs
This file contains 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 'dart:async'; | |
import 'package:flutter/material.dart'; | |
class CustomStreamBuilder<State> extends StatelessWidget { | |
final Stream stream; | |
final Widget errorWidget; | |
final Widget initialWidget; | |
final Widget Function(BuildContext context, State state) builder; | |
CustomStreamBuilder({@required this.stream, @required this.builder, this.errorWidget, this.initialWidget}); | |
@override | |
Widget build(BuildContext context) { | |
return StreamBuilder<State>( | |
stream: stream, | |
builder: (context, AsyncSnapshot<State> snapshot) { | |
if (snapshot.hasError) { | |
return errorWidget != null ? errorWidget : _buildErrorWidget(context); | |
} | |
if (!snapshot.hasData) { | |
return initialWidget != null ? initialWidget : _buildBlankWidget(context); | |
} | |
return builder(context, snapshot.data); | |
}, | |
); | |
} | |
Widget _buildErrorWidget(context) { | |
return Container(); | |
} | |
Widget _buildBlankWidget(context) { | |
return Container(); | |
} | |
} |
This file contains 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
class Screen extends StatefulWidget { | |
final AppBarBloc appBarBloc; | |
Screen({@required this.appBarBloc}); | |
@override | |
_ScreenState createState() => _ScreenState(); | |
} | |
class _ScreenState extends State<Screen> { | |
AppBarBloc _appBarBloc; | |
@override | |
Widget build(BuildContext context) { | |
return CustomStreamBuilder<AppBarState>( | |
stream: _appBarBloc.appBarTitleStream, | |
builder: (context, AppBarState state) { | |
return (state is AppBarTitleLoaded) ? Text(state.title) : Container(); | |
}, | |
); | |
} | |
@override | |
void dispose() { | |
_appBarBloc.dispose(); | |
super.dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment