Created
January 15, 2019 17:13
-
-
Save murar8/00f7bf55d3c3ee14830d39416276b0af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very good idea!! Can I use this code in my project?