使用 Flutter 初始化 Riverpod 通知程序的正确方法是什么?

问题描述 投票:0回答:1

我的模型有这个课程:

@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()
后不重置状态?

flutter riverpod
1个回答
0
投票

默认情况下,生成的提供程序是自动处置的。当没有人观看时,您的提供商正在重置。要解决此问题,请查看 keepAlive 选项。

© www.soinside.com 2019 - 2024. All rights reserved.