我在类State2中有一个appState,属性为pos.

class State2 {
  double pos = 0.9;
  String anotherProerty = "anotherproperty";
}

在使用Riverpod NotifierProvider时,我希望将pos属性用于Consumer Widget中的滑块. 不幸的是,这并不像我实现的那样起作用.无法移动滑块.

作为比较,我用一个"简单的"NotifierProvider实现了第二个Slider,它工作得很好.

你知道S出了什么问题吗?

以下是我的代码:

class Position1 extends Notifier<double> {
  @override
  double build() {
    return 0.1;
  }

  void updatePos(double newPos) {
    state = newPos;
  }
}

final position1Provider = NotifierProvider<Position1, double>(Position1.new);

class State2 {
  double pos = 0.9;
  String anotherProerty = "anotherproperty";
}

class State2Notifier extends Notifier<State2> {
  @override
  State2 build() {
    return State2();
  }

  void updatePos(double pos) {
    state.pos = pos;
  }
}

final state2Provider =
    NotifierProvider<State2Notifier, State2>(State2Notifier.new);

class RiverpodExampe1 extends ConsumerWidget {
  const RiverpodExampe1({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final pos1 = ref.watch(position1Provider);
    return Scaffold(
        appBar: AppBar(
          title: const Text("Riverpod Sample 2"),
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        ),
        body: Column(
          children: [
            Text("Pos1: $pos1"),
            Slider(
                value: pos1,
                onChanged: (newPosition) {
                  ref.read(position1Provider.notifier).updatePos(newPosition);
                }),
            Slider(
                value: ref.watch(state2Provider).pos,
                onChanged: (newPosition) {
                  ref.read(state2Provider.notifier).updatePos(newPosition);
                })
          ],
        ));
  }
}

推荐答案

当您设置状态的属性(如state.pos = pos)时,通知程序不会通知其侦听器,因为从技术上讲,状态的实例仍然是相同的(只是更改了的属性).这就是为什么它更倾向于使用immutable state来代替,以防止此类错误.

建议使用类似freezed的Package,它提供了一个copyWith方法,当您需要基于以前的状态创建一个新状态并对其属性进行很小的更改时,该方法非常有用.

然后,您可以通过执行以下操作来更新状态:

void updatePos(double pos) {
  state = state.copyWith(pos: pos);
}

可以创建一个支持可变状态的通知器提供程序,如ChangeNotifierProvider示例所示.但最好使用状态不变的NotifierProvider.

阅读更多关于不变性的内容:https://riverpod.dev/docs/concepts/why_immutability

Flutter相关问答推荐

Android Emulator冻结,但在调整窗口大小时解冻

想更新ListView上的索引点击块Flutter

如何在Flutter Webview包中触发基于URL导航的事件

Android工作室Flutter 热重新加载更新后不工作

如何使listview.builder在筛选列表后实时更新

如何在Dart中允许正则表达式中有一个空格,但允许其他字符为1或更多?

Flutter类调用另一个类中的另一个方法失败

如何在flutter中更改showModalBottomSheet小部件中CheckboxListTile小部件的值?

flutter Listview构建器溢出

Flutter中不使用Container是否可以做margin

在 Flutter 中解码 BLE 设备负载

Flutter 判断 Uint8List 是否有效 Image

Flutter 自定义对齐

如何从sibling ChildWidgetB 触发 ChildWidgetA 中的操作

如何在 Flutter 中测试动画图标

如何在 flutter 的alert 对话框中实现进度指示器?

无法在 flutter 中更新 void 方法内的变量值

仅使用 Flutter 在本地环境中托管 Web 服务器

Flutter 中的无效日期格式 2022 年 11 月 14 日

Flutter audioplayers错误-单击音频按钮时不播放音频