如何在更新 State Notifier Riverpod 中的状态之前获取旧状态?

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

我正在尝试使用 Riverpod 的 State Notifier,这是我的代码

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

如您所见,我有一种方法可以从服务器更新可用城市。但国家是一成不变的吧?我需要重新创建实例。

但我需要保留 selectedCity 之前状态的值,因为我只想更新 cities 属性

怎么做?抱歉,我是 Flutter 的新手

读取以前的状态并使用该值定义新状态。

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

使用像 freezed 这样的包使这更简单。

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