final exampleProvider = Provider.autoDispose.family<Something, MyParameter>((ref, myParameter) { print(myParameter.userId); print(myParameter.locale); // Do something with userId/locale });
@override Widget build(BuildContext context, WidgetRef ref) { int userId; // Read the user ID from somewhere final locale = Localizations.localeOf(context);
final something = ref.watch( exampleProvider(MyParameter(userId: userId, locale: locale)), );
@override List<Object> get props => [userId, locale]; }
final exampleProvider = Provider.family<Something, MyParameter>((ref, myParameter) { print(myParameter.userId); print(myParameter.locale); // Do something with userId/locale });
@override Widget build(BuildContext context, WidgetRef ref) { int userId; // Read the user ID from somewhere final locale = Localizations.localeOf(context);
final something = ref.watch( exampleProvider(MyParameter(userId: userId, locale: locale)), );
final myProvider = FutureProvider.autoDispose((ref) async { // An object from package:dio that allows cancelling http requests final cancelToken = CancelToken(); // When the provider is destroyed, cancel the http request ref.onDispose(() => cancelToken.cancel());
// Fetch our data and pass our `cancelToken` for cancellation to work final response = await dio.get('path', cancelToken: cancelToken); // If the request completed successfully, keep the state ref.maintainState = true; return response; });
final firstProvider = Provider.autoDispose((ref) => 0);
final secondProvider = Provider((ref) { // The argument type 'AutoDisposeProvider<int>' can't be assigned to the // parameter type 'AlwaysAliveProviderBase<Object, Null>' ref.watch(firstProvider); });
final firstProvider = Provider.autoDispose((ref) => 0);
final secondProvider = Provider.autoDispose((ref) { ref.watch(firstProvider); });
WidgetRef
获取WidgetRef对象
从其他Provider对象中获取
1 2 3 4 5
final provider = Provider((ref) { // use ref to obtain other providers final repository = ref.watch(repositoryProvider); return SomeValue(repository); })
@override Widget build(BuildContext context, WidgetRef ref) { // use ref to listen to a provider final counter = ref.watch(counterProvider); return Text('$counter'); } }
classHomeViewStateextendsConsumerState<HomeView> { @override void initState() { super.initState(); // "ref" can be used in all life-cycles of a StatefulWidget. ref.read(counterProvider); }
@override Widget build(BuildContext context) { // We can also use "ref" to listen to a provider inside the build method final counter = ref.watch(counterProvider); return Text('$counter'); } }
@override Widget build(BuildContext context, WidgetRef ref) { // HookConsumerWidget allows using hooks inside the build method final state = useState(0);
// We can also use the ref parameter to listen to providers. final counter = ref.watch(counterProvider); return Text('$counter'); } }