What is the right way to init a Riverpod notifier with Flutter?

39 Views Asked by At

I have these classes for my model:

@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;
  }

}

The price for one single item is changed from another notifier:

@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);
  }
}

The flow is working as expected but every time the build() method of GeneratorsNotifier is called, the state gets reset to the initial values. That does not happen for example for the build() in GameStatusNotifier (and for another example in documentation). How can I fix GeneratorsNotifier to not reset the status after build() is called?

2

There are 2 best solutions below

0
Randal Schwartz On BEST ANSWER

By default, generated providers are autodispose. Your provider is resetting when nobody watches it. To fix that, review the keepAlive options.

0
Leo Chen On

keepalive or watch the provider in your widget build where you want to keep.