Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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++;
}

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

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

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: []

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?


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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

The syntax for declaring your StateNotifierProvider is now as follows:

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

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);

More on the changes here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...