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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| // ignore_for_file: prefer_const_constructors_in_immutables
import 'package:flutter/material.dart'; import 'package:provider/provider.dart';
/// Provider封装类 方便数据初始化 class ProviderWidget<T extends ChangeNotifier> extends StatefulWidget { final ValueWidgetBuilder<T> builder; final T model; final Widget? child; final Function(T model)? onModelReady; final bool autoDispose;
ProviderWidget({ Key? key, required this.builder, required this.model, this.child, this.onModelReady, this.autoDispose = true, }) : super(key: key);
_ProviderWidgetState<T> createState() => _ProviderWidgetState<T>(); }
class _ProviderWidgetState<T extends ChangeNotifier> extends State<ProviderWidget<T>> { late T model;
@override void initState() { model = widget.model; widget.onModelReady?.call(model); super.initState(); }
@override void dispose() { if (widget.autoDispose) model.dispose(); super.dispose(); }
@override Widget build(BuildContext context) { return ChangeNotifierProvider<T>.value( value: model, child: Consumer<T>( builder: widget.builder, child: widget.child, ), ); } }
class ProviderWidget2<A extends ChangeNotifier, B extends ChangeNotifier> extends StatefulWidget { final Widget Function(BuildContext context, A model1, B model2, Widget? child) builder; final A model1; final B model2; final Widget? child; final Function(A model1, B model2)? onModelReady; final bool autoDispose;
ProviderWidget2({ Key? key, required this.builder, required this.model1, required this.model2, this.child, this.onModelReady, this.autoDispose = true, }) : super(key: key);
_ProviderWidgetState2<A, B> createState() => _ProviderWidgetState2<A, B>(); }
class _ProviderWidgetState2<A extends ChangeNotifier, B extends ChangeNotifier> extends State<ProviderWidget2<A, B>> { late A model1; late B model2;
@override void initState() { model1 = widget.model1; model2 = widget.model2; widget.onModelReady?.call(model1, model2); super.initState(); }
@override void dispose() { if (widget.autoDispose) { model1.dispose(); model2.dispose(); } super.dispose(); }
@override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<A>.value(value: model1), ChangeNotifierProvider<B>.value(value: model2), ], child: Consumer2<A, B>( builder: widget.builder, child: widget.child, )); } }
|