【问题标题】:StateNotifier with riverpod带有 Riverpod 的 StateNotifier
【发布时间】:2021-04-21 18:56:31
【问题描述】:

我正在尝试使用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));
});

【问题讨论】:

标签: flutter dart flutter-provider riverpod


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    class Drawer with ChangeNotifier{
    
      void toggleDrawer(){
        if(state.isOpen == true){
      
    notifyListeners();
        }else{
    
    notifyListeners();
        }
      }
    }
    

    会有用的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-04
      • 2021-11-27
      • 2022-01-17
      • 2021-03-17
      • 1970-01-01
      • 2021-12-01
      • 2021-05-24
      • 2021-10-28
      相关资源
      最近更新 更多