Skip to content

Instantly share code, notes, and snippets.

@putraxor
Created February 7, 2019 12:55
Show Gist options
  • Save putraxor/34699fc2f861ca7606d79218b364049a to your computer and use it in GitHub Desktop.
Save putraxor/34699fc2f861ca7606d79218b364049a to your computer and use it in GitHub Desktop.
Multiple Blocs Provider for Flutter
import 'package:flutter/material.dart';
import 'package:model/blocs/base_bloc.dart';
/// Used to give [child] and all it's subsequent children access to [blocs].
/// To get a reference to 'SomeBloc' from a child use: BlocsProvider.of<SomeBloc>(context)
class BlocsProvider extends StatefulWidget {
BlocsProvider({Key key, @required this.child, @required this.blocs})
: super(key: key);
final Widget child;
final List<BaseBloc> blocs;
_BlocsProviderState createState() => _BlocsProviderState();
static T of<T extends BaseBloc>(BuildContext context) {
_InheritedBlocProvider provider = context
.ancestorInheritedElementForWidgetOfExactType(_InheritedBlocProvider)
.widget;
return provider.blocs.lastWhere((bloc) => bloc is T);
}
}
class _BlocsProviderState extends State<BlocsProvider> {
@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<BaseBloc> blocs;
@override
bool updateShouldNotify(_InheritedBlocProvider oldWidget) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment