[英]Flutter Riverpod/Provider: Setting an initial state for a stateNotifier
[英]Flutter Riverpod v1.0 - state not updating with StateNotifier List
我从 RiverPod 0.4x 迁移到 1.0 稳定版,现在这个 StateNotifier 不再更新 state 即使在 Z6F1C25ED1523962BEE9 结束时调用move()
function (debugPrint 显示调用)。 这在 0.4x 中工作,但显然在改进的 1.0 RiverPod 中我还没有完全迁移。
当 state 是列表时,RiverPod 1.0 更新 state 缺少什么?
final animateCoversStateNotifierProvider = StateNotifierProvider.autoDispose<
AnimateCoversStateNotifier,
List<CoverAlignment>>((ref) => AnimateCoversStateNotifier());
class AnimateCoversStateNotifier extends StateNotifier<List<CoverAlignment>> {
AnimateCoversStateNotifier() : super([]);
void addCover({
required CoverAlignment alignment,
}) =>
state.add(alignment);
void move({
required int cover,
bool? readyToOpen,
bool? speechBalloonVisible,
Duration? animatedOpacityDuration,
bool? removeSpeechBalloonPadding,
}) {
debugPrint('move cover called');
Future.delayed(const Duration(milliseconds: 200), () {
if (mounted) {
state[cover].removeSpeechPadding = speechBalloonVisible != true;
state[cover].speechBalloonOpacity =
speechBalloonVisible == true ? kMaxSpeechBalloonOpacity : 0.0;
state[cover].x = CoverAlignment.randomDouble();
state[cover].y = CoverAlignment.randomDouble();
state[cover].curve = CoverAlignment.getCurve();
state[cover].seconds = CoverAlignment.randomSeconds();
state[cover].degrees = CoverAlignment.randomIntInRangeWithMinimum(
min: 0,
max: 45,
);
/// This was required to update state using RiverPod 0.4x, but no longer works in
/// RiverPod 1.0.
state = state;
}
});
}
}
在我的构建屏幕主体中,我使用watch
来响应通知者的更改。
/// Display covers
final List coverAlignment =
ref.watch(animateCoversStateNotifierProvider);
正在做:
state = state
从来不应该工作。
你不应该改变现有的 state。 你应该克隆 state
相反,请执行以下操作:
state[cover] = state[cover].copyWith(
removeSpeechPadding: speechBalloonVisible != true,
...
),
您可以使用Freezed生成此copyWith
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.