我的模型有这个课程:
@freezed
class Generator with _$Generator {
factory Generator({
required int id,
required double cost,
}) = _Generator;
factory Generator.fromJson(Map<String, Object?> json) => _$GeneratorFromJson(json);
}
@riverpod
class GeneratorsNotifier extends _$GeneratorsNotifier {
@override
List<Generator> build() {
return [
for (final g in [
{
'id': 0,
'cost': 2.63,
},
{
'id': 1,
'cost': 20.63,
},
{
'id': 2,
'cost': 139.63,
},
{
'id': 3,
'cost': 953.63,
},
{
'id': 4,
'cost': 5653.63,
},
]) Generator.fromJson(g)
];
}
void addGenerator(Map<String, Object?> json) {
state = [...state, Generator.fromJson(json)];
}
void changePrice(int id) {
state = [
for (final generator in state)
if (generator.id == id)
_createUpdatedGenerator(generator)
else
generator,
];
}
Generator _createUpdatedGenerator(Generator generator) {
double newPrice = ...some logic here...
Generator updatedGenerator = generator.copyWith(
price: newPrice,
);
return updatedGenerator;
}
}
另一通知者更改了一件商品的价格:
@riverpod
class GameStatusNotifier extends _$GameStatusNotifier {
@override
GameStatus build() {
return GameStatus(
// some params
);
}
void changePrice(int id) {
state = ...some logic here that change the status...
// now try to update the status of GeneratorsNotifier
ref.read(generatorsNotifierProvider.notifier).changePrice(id);
}
}
流程按预期工作,但每次调用
build()
的 GeneratorsNotifier
方法时,状态都会重置为初始值。例如,对于 build()
中的 GameStatusNotifier
(以及文档中的其他示例),这种情况不会发生。如何修复 GeneratorsNotifier
使其在调用 build()
后不重置状态?
默认情况下,生成的提供程序是自动处置的。当没有人观看时,您的提供商正在重置。要解决此问题,请查看 keepAlive 选项。