Skip to content

Instantly share code, notes, and snippets.

@mono0926
Last active November 2, 2020 08:53
Show Gist options
  • Save mono0926/8d498eb8a5f0f89cfc9319fb96159a72 to your computer and use it in GitHub Desktop.
Save mono0926/8d498eb8a5f0f89cfc9319fb96159a72 to your computer and use it in GitHub Desktop.
import 'package:flutter/widgets.dart';
abstract class Bloc {
void dispose();
}
class BlocProvider<BlocType extends Bloc> extends StatefulWidget {
final WidgetBuilder builder;
final BlocType Function() creator;
BlocProvider({
@required Widget child,
@required BlocType Function() creator,
}) : this.builder(
builder: (context) => child,
creator: creator,
);
BlocProvider.builder({
@required this.builder,
@required this.creator,
});
@override
_BlocProviderState createState() => _BlocProviderState<BlocType>();
static BlocType of<BlocType extends Bloc>(BuildContext context) =>
_Inherited.of<BlocType>(context);
}
class _BlocProviderState<BlocType extends Bloc>
extends State<BlocProvider<BlocType>> {
BlocType _bloc;
@override
Widget build(BuildContext context) {
return _Inherited<BlocType>(
bloc: _bloc,
child: Builder(builder: (context) => widget.builder(context)),
);
}
@override
void initState() {
super.initState();
_bloc = widget.creator();
}
@override
void dispose() {
_bloc.dispose();
super.dispose();
}
}
class _Inherited<BlocType extends Bloc> extends InheritedWidget {
final BlocType bloc;
_Inherited({
@required this.bloc,
@required Widget child,
}) : super(child: child);
static BlocType of<BlocType extends Bloc>(BuildContext context) {
Type typeOf<T>() => T;
return (context
.ancestorInheritedElementForWidgetOfExactType(
typeOf<_Inherited<BlocType>>())
.widget as _Inherited<BlocType>)
.bloc;
}
@override
bool updateShouldNotify(_Inherited oldWidget) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment