我正在尝试使用 Riverpod 的状态通知程序,这是我的代码
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 新手
答案 0 :(得分:0)
读取之前的状态并使用该值来定义新状态。
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));