简体   繁体   中英

StateNotifier with riverpod

I'm trying to use riverpod stateNotifier to toggle open and close a drawer. The intent was if the drawer is open then the homescreen would shrink/grow via the AnimatedContainer. I'm not sure what the problem is but the value x and y is not being read or watch by the AnimatedContainer. Plus am I using stateNotifier correctly?

Home screen

@override
Widget build(BuildContext context) {
  return SafeArea(
    child: Consumer(
      builder: (context, watch, child) {
        final drawer = watch(drawerProvider).state;
        return GestureDetector(
          onTap: () {
            if(drawer.isOpen){
              context.read(drawerProvider).toggleDrawer();
            }
          },
          child: AnimatedContainer(
            transform: Matrix4.translationValues(MediaQuery.of(context).size.height * drawer.x,MediaQuery.of(context).size.height * drawer.y, 0)..scale(drawer.scale),
            duration: Duration(milliseconds: 250),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(drawer.isOpen ? 20 : 0)),
            child:Container(
                ),
            ),
          );
      },
    ),
  );
}

Drawer Provider

import 'package:flutter_riverpod/all.dart';

class Drawer{
  double x,y,scale;
  bool isOpen;
  Drawer(this.x,this.y,this.scale,this.isOpen);
}

class DrawerNotifier extends StateNotifier<Drawer>{
  DrawerNotifier(Drawer state) : super(Drawer(0.5,0.1,0.8,true));
  void toggleDrawer(){
    if(state.isOpen == true){
      print(true);
      state.x = 0;
      state.y = 0;
      state.scale = 1;
      state.isOpen = false;
    }else{
      print(false);
      state.x = 0.5;
      state.y = 0.1;
      state.scale = 0.8;
      state.isOpen = true;
    }
  }
}

final drawerProvider = StateNotifierProvider((ref){
  return DrawerNotifier(Drawer(0.5,0.1,0.8,true));
});

You're not changing the == of the Drawer itself. It's the same Object both before and after the update of its members. You need to either create overrides for == and hashCode that properly reflect the member values, or switch to a different provider that requires notify_listeners when the "state" is changed.

class Drawer with ChangeNotifier{

  void toggleDrawer(){
    if(state.isOpen == true){
  
notifyListeners();
    }else{

notifyListeners();
    }
  }
}

It will Work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM