【发布时间】:2021-11-27 04:40:27
【问题描述】:
我从 RiverPod 0.4x 迁移到 1.0 stable,现在这个 StateNotifier 不再更新状态,即使动画结束时正在调用 move() 函数(debugPrint 显示调用)。这在 0.4x 中工作,但显然在改进的 1.0 RiverPod 中我还没有完全迁移。
当状态是列表时,RiverPod 1.0 缺少什么来更新状态?
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);
编辑:按照 Remi 在 cmets 中的建议创建 Freezed 类
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
import 'package:myapp/app/corral/models/cover_alignment_model.dart';
part 'animate_covers.freezed.dart';
class AnimateCovers extends StateNotifier<List<CoverAlignment>>
with _$AnimateCovers {
factory AnimateCovers() = _AnimateCovers;
void addCover({
required int cover,
required CoverAlignment alignment,
}) {
state.insert(cover, alignment);
}
void move({
required int cover,
bool? readyToOpen,
bool? speechBalloonVisible,
Duration? animatedOpacityDuration,
bool? removeSpeechBalloonPadding,
}) {
/// What do I do here?
}
}
【问题讨论】: