13

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

Giorgio
  • 2,137
  • 3
  • 20
  • 40

2 Answers2

24

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.

Alex Hartford
  • 5,110
  • 2
  • 19
  • 36
  • 1
    Thank you!!! Why isn't this on the `StateNotifierProvider` class docs. I've been struggling for about a day trying to get this to work. https://pub.dev/documentation/riverpod/latest/riverpod/StateNotifierProvider-class.html – David Jun 14 '21 at 17:40
  • Edit: Just noticed the docs have been updated in master, I guess the next time it's published the docs will have the new API. – David Jun 14 '21 at 17:50
1

You may also use dynamic to accept any type if value for the StateNotifierProvider

final modelProvider =
    StateNotifierProvider.autoDispose<ModelClassName, dynamic>(
        (ref) => ModelClassName());
FEELIX
  • 407
  • 4
  • 8