-
-
Save boeledi/cb9b933b2e2664ae1ee5cc78b0da273a 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'; | |
typedef BlocBuilder<T> = T Function(); | |
typedef BlocDisposer<T> = Function(T); | |
abstract class BlocBase { | |
void dispose(); | |
} | |
class BlocProvider<T extends BlocBase> extends StatefulWidget { | |
const BlocProvider({ | |
super.key, | |
required this.child, | |
required this.blocBuilder, | |
this.blocDispose, | |
}); | |
final Widget child; | |
final BlocBuilder<T> blocBuilder; | |
final BlocDisposer<T>? blocDispose; | |
@override | |
_BlocProviderState<T> createState() => _BlocProviderState<T>(); | |
static T? of<T extends BlocBase>(BuildContext context) { | |
final InheritedElement? inheritedElement = context.getElementForInheritedWidgetOfExactType<_BlocProviderInherited<T>>(); | |
if (inheritedElement == null) { | |
return null; | |
} | |
final _BlocProviderInherited<T>? provider = inheritedElement.widget as _BlocProviderInherited<T>?; | |
return provider?.bloc; | |
} | |
} | |
class _BlocProviderState<T extends BlocBase> extends State<BlocProvider<T>> { | |
late T bloc; | |
@override | |
void initState() { | |
super.initState(); | |
bloc = widget.blocBuilder(); | |
} | |
@override | |
void dispose() { | |
if (widget.blocDispose != null) { | |
widget.blocDispose?.call(bloc); | |
} else { | |
bloc.dispose(); | |
} | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return _BlocProviderInherited<T>( | |
bloc: bloc, | |
child: widget.child, | |
); | |
} | |
} | |
class _BlocProviderInherited<T extends BlocBase> extends InheritedWidget { | |
const _BlocProviderInherited({ | |
Key? key, | |
required Widget child, | |
required this.bloc, | |
}) : super(key: key, child: child); | |
final T bloc; | |
@override | |
bool updateShouldNotify(_BlocProviderInherited<T> oldWidget) => false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First off, Love this code! It has made my life so easy! However, I ran into an issue where I was trying to use my bloc in a dialog, so was creating a custom builder in show dialog. I needed to make it a BlocProvider, since I was modifying the bloc in that dialog. So I just passed in my existing bloc. However, when I closed that dialog, it also got rid of my BlocProvider, and called the dispose() method, which closed the dispose method of my existing bloc. Which in turn closed all the streams on the bloc, and caused big issues.
I don't know the best way to do, but I added a parameter to the BlocProvider which determines if the bloc should be disposed. My changes are below. Just thought I'd pass along!