'StateNotifierProvider' 类型声明有 2 个类型参数,但给出了 1 个类型参数 [英] The type 'StateNotifierProvider' is declared with 2 type parameters, but 1 type arguments were given

查看:36
本文介绍了'StateNotifierProvider' 类型声明有 2 个类型参数,但给出了 1 个类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我想用 Riverpod 管理状态的 Flutter 2.0.5 应用程序的上下文中,我想我可以像这样声明一个 StateNotifierProvider:

In the context of a Flutter 2.0.5 app whose state I'd like to manage with Riverpod, I thought I can declare a StateNotifierProvider like this:

import 'package:flutter_riverpod/flutter_riverpod.dart';


final counterProvider = StateNotifierProvider<CounterStateNotifier>((ref) => CounterStateNotifier());

class CounterStateNotifier extends StateNotifier<int> {
  CounterStateNotifier([int count = 0]) : super(count);

  void increment() => state++;
}

但是 Android Studio(以及后来的 Dart 编译器)抱怨我声明 counterProvider 变量的行:

But Android Studio (and later the Dart compiler as well) complains about the line where I declare the counterProvider variable:

'StateNotifierProvider' 类型声明有 2 个类型参数,但给出了 1 个类型参数.

The type 'StateNotifierProvider' is declared with 2 type parameters, but 1 type arguments were given.

删除 类型参数在 StateNotifierProvider 中删除错误.但是,尝试读取提供程序并调用其 increment 方法(将 () => context.read(counterProvider).increment() 设置为 onPressed 一个 ElevatedButton,然后按下按钮)给出以下运行时错误:

Removing the <CounterStateNotifier> type parameter in StateNotifierProvider<CounterStateNotifier> removes the error. However, attempting to read the provider and call its increment method (setting () => context.read(counterProvider).increment() as the onPressed of an ElevatedButton, then pressing the button) gives the following runtime error:

'increment'
method not found
Receiver: 0
Arguments: []

为什么 context.read(counterProvider) 返回 int 状态而不是通知程序?我的问题第一部分提到的类型参数错误背后的原因是什么?

Why is context.read(counterProvider) returning the int state instead of the notifier? And what is the reason behind the type parameter error mentioned in the first part of my question?

我应该提到我正在网络上运行我的应用程序(使用 flutter run -d Chrome).

I should mention that I'm running my app on the web (with flutter run -d Chrome).

推荐答案

从 Riverpod 0.14.0 开始,State 是 StateNotifierProvider 公开的默认值.

As of Riverpod 0.14.0, State is the default value exposed by StateNotifierProvider.

现在声明 StateNotifierProvider 的语法如下:

The syntax for declaring your StateNotifierProvider is now as follows:

final counterProvider = StateNotifierProvider<CounterStateNotifier, int>((ref) => CounterStateNotifier());

访问函数现在需要添加 .notifier(访问 StateNotifier 本身):

Accessing functions now requires adding .notifier (accessing the StateNotifier itself):

context.read(counterProvider.notifier).increment();

正如您所注意到的,您现在可以像这样访问状态:

And like you've noticed, you now access the state like so:

final count = context.read(counterProvider);

此处详细了解变化.

这篇关于'StateNotifierProvider' 类型声明有 2 个类型参数,但给出了 1 个类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆