0

我正在尝试使用 Riverpod stateNotifier 来打开和关闭抽屉。目的是如果抽屉打开,那么主屏幕将通过 AnimatedContainer 缩小/增长。我不确定问题是什么,但值 x 和 y 没有被 AnimatedContainer 读取或观察。另外我正确使用 stateNotifier 吗?

主屏幕

@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(
                ),
            ),
          );
      },
    ),
  );
}

抽屉供应商

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));
});
4

2 回答 2

1

你没有改变抽屉本身的 == 。在其成员更新之前和之后,它都是同一个对象。您需要为 == 和 hashCode 创建正确反映成员值的覆盖,或者切换到notify_listeners“状态”更改时需要的不同提供程序。

于 2021-01-17T18:08:34.593 回答
0
class Drawer with ChangeNotifier{

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

notifyListeners();
    }
  }
}

它会工作

于 2021-01-17T18:26:28.403 回答