Skip to content

Instantly share code, notes, and snippets.

@murar8
Created January 15, 2019 17:13
Show Gist options
  • Save murar8/00f7bf55d3c3ee14830d39416276b0af to your computer and use it in GitHub Desktop.
Save murar8/00f7bf55d3c3ee14830d39416276b0af to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
abstract class Bloc<BlocEvent, BlocState> {
void dispose();
}
/// Used to give [child] and all it's subsequent children access to [blocs].
/// To get a reference to 'SomeBloc' from a child use: MultipleBlocProvider.of<SomeBloc>(context)
class MultipleBlocProvider extends StatefulWidget {
MultipleBlocProvider({Key key, @required this.child, @required this.blocs})
: super(key: key);
final Widget child;
final List<Bloc> blocs;
_MultipleBlocProviderState createState() => _MultipleBlocProviderState();
static T of<T extends Bloc>(BuildContext context) {
_InheritedBlocProvider provider = context
.ancestorInheritedElementForWidgetOfExactType(_InheritedBlocProvider)
.widget;
return provider.blocs.lastWhere((bloc) => bloc is T);
}
}
class _MultipleBlocProviderState extends State<MultipleBlocProvider> {
@override
Widget build(BuildContext context) => _InheritedBlocProvider(
blocs: widget.blocs,
child: widget.child,
);
@override
void dispose() {
widget.blocs.map((bloc) => bloc.dispose());
super.dispose();
}
}
class _InheritedBlocProvider extends InheritedWidget {
_InheritedBlocProvider({Key key, this.child, this.blocs})
: super(key: key, child: child);
final Widget child;
final List<Bloc> blocs;
@override
bool updateShouldNotify(_InheritedBlocProvider oldWidget) => false;
}
@baeharam
Copy link

Very good idea!! Can I use this code in my project?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment