Skip to content

Instantly share code, notes, and snippets.

@magillus
Last active March 19, 2019 03:22
Show Gist options
  • Save magillus/fd2e9ea58a77b4661fe1cc2eea371da4 to your computer and use it in GitHub Desktop.
Save magillus/fd2e9ea58a77b4661fe1cc2eea371da4 to your computer and use it in GitHub Desktop.
StreamBuilderFiltered - For filtered and cast streams.
abstract class MyBlocState{}
class Step1State extends MyBlocState{
String title;
}
class Step2State extends MyBlocState{
int progress;
}
class Step3State extends MyBlocState{
}
/// Example of showing only step2 details
example() {
var widget= StreamBuilderFilter<Step2State>(
noData: LinearProgressIndicator(),
stream: myBloc.state,
builder: (context, data) {
return Text("Progress: ${data.progress}");
},
);
}
/// I found useful to have this little function and build the StreamBuilderFilter around with it.
/// When ever BLoC state is returned as base class some views only react to some state and this helps to create filtered stream builder.
/// Data Widget builder to build widget with provided data type.
typedef DataWidgetBuilder<T> = Widget Function(BuildContext context, T data);
/// Stream builder with filtering by T type, or noData
class StreamBuilderFilter<T> extends StreamBuilder {
/// [stream] - main stream that sends any type
/// [noData] - widget returned on build when no data of desired type is streamed
/// [dataBuilder] - builder with the expected data type
StreamBuilderFilter(
{Key key, Stream stream, Widget noData, DataWidgetBuilder<T> dataBuilder})
: super(key: key, stream:stream, builder: (c,s)=>_internalBuilder(c,s, dataBuilder, noData));
/// Super constructor requires static method
static Widget _internalBuilder<T>(BuildContext context, AsyncSnapshot snapshot, DataWidgetBuilder<T> dataBuilder, Widget noData) {
if (snapshot.hasData && snapshot.data is T) {
return dataBuilder(context, snapshot.data);
} else {
/// show noData widget or empty container
return noData??Container();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment