Skip to content

Instantly share code, notes, and snippets.

@DFelten
Last active July 19, 2019 10:46
Show Gist options
  • Save DFelten/c00529f9641c738126d1360e692f21e0 to your computer and use it in GitHub Desktop.
Save DFelten/c00529f9641c738126d1360e692f21e0 to your computer and use it in GitHub Desktop.
Custom Stream Builder for Flutter BLoCs
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();
}
}
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