Skip to content

Instantly share code, notes, and snippets.

@javaherisaber
Last active September 18, 2022 11:09
Show Gist options
  • Save javaherisaber/d3b66df959b71674eb4c3c6dcaffacb6 to your computer and use it in GitHub Desktop.
Save javaherisaber/d3b66df959b71674eb4c3c6dcaffacb6 to your computer and use it in GitHub Desktop.
BlocProvider
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
abstract class BlocBase {
void dispose();
}
class BlocProvider<T extends BlocBase> extends StatefulWidget {
const BlocProvider({
super.key,
required this.bloc,
required this.child,
});
final T bloc;
final Widget child;
@override
BlocProviderState<T> createState() => _BlocProviderState<T>();
static T of<T extends BlocBase>(BuildContext context){
final provider = context.findAncestorWidgetOfExactType() as BlocProvider<T>?;
if (provider == null) {
throw 'Widget not found in BlocProvider tree';
}
return provider.bloc;
}
}
class BlocProviderState<T> extends State<BlocProvider<BlocBase>>{
@override
void dispose(){
widget.bloc.dispose();
super.dispose();
}
@override
Widget build(BuildContext context){
return widget.child;
}
}
// An example bloc class to showcase how to use it
class ExampleBloc implements BlocBase {
final _isFavorite = BehaviorSubject<bool>();
Stream<bool> get isFavorite => _isFavorite.stream;
@override
void dispose() {
_isFavorite.close();
}
}
// How to create a page widget
BlocProvider<ExampleBloc>(
bloc: ExampleBloc(),
child: YouPage(),
);
// How to get bloc in children
final bloc = BlocProvider.of<ExampleBloc>(context);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment