1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| class CustomProvider<T extends Listenable> extends StatefulWidget { final T Function() create; final Widget child; const CustomProvider({Key? key, required this.child, required this.create}) : super(key: key);
@override State<CustomProvider> createState() => _CustomState<T>();
static T of<T>(BuildContext context,{bool listen = true}) { if(listen) { return context.dependOnInheritedWidgetOfExactType<CustomInheritedWidget<T>>()!.model; } else { return (context.getElementForInheritedWidgetOfExactType<CustomInheritedWidget<T>>()!.widget as CustomInheritedWidget).model; }
} }
class _CustomState<T extends Listenable> extends State<CustomProvider<T>> {
late T model;
@override void initState() { super.initState(); model = widget.create(); }
@override Widget build(BuildContext context) { return AnimatedBuilder( animation: model, builder: (BuildContext context, Widget? child) { return CustomInheritedWidget(model: model, child: widget.child); }, ); } }
class CustomInheritedWidget<T> extends InheritedWidget { final T model;
const CustomInheritedWidget({super.key, required this.model,required super.child});
static CustomInheritedWidget of<T>(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<CustomInheritedWidget<T>>()!; }
@override bool updateShouldNotify(covariant InheritedWidget oldWidget) { print("update"); return true; } }
extension Consumer on BuildContext { T watch<T>() => CustomProvider.of(this); T read<T>() => CustomProvider.of(this,listen: false); }
|