5

I'm confused about how to use stateNotifier with riverpod. Most of the tutorials out there uses the counter example which is good but still not that clear to me. I'm trying to implement a stateNotifier with 2 states : isDrawerOpen and isDrawerColor which returns boolean result. Some functions will trigger the changes in those state. Below is what I have implemented and could really use some clarification.

import 'package:flutter_riverpod/all.dart';

class DrawerNotifier extends StateNotifier{

  DrawerNotifier() : super(false);

  bool isDrawerOpen = false;
  bool isDrawerColor = false;
  
  void toggleDrawer() {
    isDrawerOpen = !isDrawerOpen;
  }
  void toggleColor() {
    isDrawerColor = !isDrawerColor;
  }
}

final drawerProvider = StateNotifierProvider((_) => DrawerNotifier());

final isDrawerOpen = StateNotifierProvider((ref){
  final state = ref.watch(drawerProvider);
  return state.isDrawerOpen;
});

final isDrawerColor = StateNotifierProvider((ref){
  final state = ref.watch(drawerProvider);
  return state.isDrawerColor;
});
stalwart1014
  • 451
  • 1
  • 9
  • 29

1 Answers1

3

You can create a seperate state class as below(I am using the equattable package)

abstract class DrawerState extends Equatable {
  DrawerState();
  }
class IsDrawerOpen extends DrawerState {
 UserFetchInitial();

 @override
 List<Object> get props => [];
}
class IsDrawerClosed extends DrawerState {
 UserFetched();

 @override
 List<Object> get props => [];
}

Next, your drawerProvider will look like this. We will create a drawer Controller to control the state of the drawers.

final drawerProvider = StateNotifierProvider<DrawerController>((_) => DrawerNotifier());

Our DrawerController will look like this.

class DrawerController extends StateNotifier<DrawerState> { 
  void changeDrawer(bool isDrawerOpened) {
   if(isDrawerOpened) {
      state = IsDrawerOpen();
    } else { 
        state = IsDrawerClosed();
      }
  }
}

You can call the changeDrawer method anywhere in your UI using context.read(drawerProvider).changeDrawer(true);

Tayormi
  • 1,150
  • 8
  • 12