Agung
Agung

Reputation: 13803

how to get the old state before updating the state in State Notifier Riverpod?

I am trying to use State Notifier from Riverpod, here is my code

import 'package:flutter_riverpod/flutter_riverpod.dart';

class CitiesState {
  List<String> cities = [];
  String selectedCity = "New York";

  CitiesState({required this.cities, required this.selectedCity});
}

class ChooseCityPageModel extends StateNotifier<AsyncValue<CitiesState>> {
  ChooseCityPageModel() : super(AsyncValue.loading());

  Future<void> updateCitiesData() async {
    state = AsyncValue.loading();

    try {
      final latestCities = await myAPI.getAvailableCities();
      state = AsyncValue.data(
        ChooseCityPageState(
          selectedCity: '??????', // <------ I need to get the previous selectedCity state
          cities: latestCities, // <---- because I just want to update available cities
        ),
      );
    } catch (error) {
      state = AsyncValue.error(error);
    }
  }
}

as you can see, I have a method to update available cities from Server. but the state is immutable right? and I need to create the instance again.

but I need to keep the value of selectedCity from previous state, because I just want to update the cities property

how to do that? sorry I am new in Flutter

Upvotes: 0

Views: 1980

Answers (1)

Alex Hartford
Alex Hartford

Reputation: 5970

Read the previous state and use that value to define the new state.

state = AsyncValue.data(
  CitiesState(
    selectedCity: state.data!.value.selectedCity,
    cities: latestCities,
  ),
);

Utilizing a package like freezed makes this even simpler.

@freezed
class CitiesState with _$CitiesState {
  const factory CitiesState({
    required List<String> cities,
    required String selectedCity,
  }) = _CitiesState;
}

state = AsyncValue.data(state.data!.value.copyWith(cities: latestCities));

Upvotes: 1

Related Questions