Home > database >  class that indirectly extends from StateNotifier in StateNotifierProvider doesn't work
class that indirectly extends from StateNotifier in StateNotifierProvider doesn't work

Time:12-23

I want to use a class that indirectly extends from StateNotifier in StateNotifierProvider, but it doesn't work.

    import 'package:riverpod/riverpod.dart';
    
    abstract class BaseDog {}
    class Shiba extends BaseDog {}
    
    
    abstract class BaseDogListController
        extends StateNotifier<AsyncValue<List<BaseDog>>> {
      BaseDogListController() : super(const AsyncValue.loading());
    //doing something with state.
    }
    class ShibaListController extends BaseDogListController {}
    
    
    final shibaListControllerProvider =
        StateNotifierProvider<ShibaListController//←this code is error, AsyncValue<List<Shiba>>>(
            (_) => ShibaListController());

here is out put:

'ShibaListController' doesn't conform to the bound 'StateNotifier<AsyncValue<List>>' of the type parameter 'Notifier'. Try using a type that is or is a subclass of 'StateNotifier<AsyncValue<List>>'.

the use of state in BaseDogListController is the reason why it does not directly extends from StateNotifier.

How can I solve this?

CodePudding user response:

The problem is how you defined your provider

It says that it uses the ShibaListController – which has for state AsyncValue<List<BaseDog>>, yet you're telling the provider that its state is defined as AsyncValue<List<Shiba>>

These types don't match.

You likely want to make BaseDogListController generic:

abstract class BaseDogListController<DogType extends BaseDog>
    extends StateNotifier<AsyncValue<List<DogType>>> {
  BaseDogListController() : super(const AsyncValue.loading());
//doing something with state.
}

class ShibaListController extends BaseDogListController<Shiba> {}
  • Related