Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 236
Giorgio Avatar asked Apr 23 '21 16:04

Giorgio


Video Answer


1 Answers

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

final modelProvider =
    StateNotifierProvider.autoDispose<ModelClassName, dynamic>(
        (ref) => ModelClassName());
like image 186
FEELIX Avatar answered Oct 16 '22 17:10

FEELIX