我正在尝试使用 riverpod stateNotifier 来切换打开和关闭抽屉。目的是如果抽屉打开,则主屏幕将通过 AnimatedContainer 缩小/增长。我不确定问题是什么,但是 AnimatedContainer 没有读取或监视值 x 和 y。另外我是否正确使用 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));
});
答案 0 :(得分:1)
您不会更改 Drawer 本身的 ==。它的成员更新前后都是同一个对象。您需要为 == 和 hashCode 创建覆盖以正确反映成员值,或者在“状态”更改时切换到需要 notify_listeners
的其他提供程序。
答案 1 :(得分:0)
class Drawer with ChangeNotifier{
void toggleDrawer(){
if(state.isOpen == true){
notifyListeners();
}else{
notifyListeners();
}
}
}
它会起作用