Flutter Riverpod v1.0-状态未使用StateNotifier列表更新



我从RiverPod 0.4x迁移到了1.0稳定版,现在这个StateNotifier不再更新状态,即使在动画结束时正在调用move()函数(debugPrint显示调用(。这在0.4x中起作用,但很明显,在改进的1.0 RiverPod中,我还没有完全迁移。

当状态为List时,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);

EDIT:创建一个自由类作为Remi在评论中的建议

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?
}
}

执行:

state = state

根本不应该工作。

你不应该改变现有的状态。你应该克隆状态

相反,做一些类似的事情:

state[cover] = state[cover].copyWith(
removeSpeechPadding: speechBalloonVisible != true,
...
),

您可以使用Freezed 生成此copyWith方法

最新更新