[英]Riverpod state class default value
例如,我有帶有一堆字段的ProfileModel
類
他們中的許多人沒有默認值,除非他們在我從后端獲取用戶信息時正在初始化
使用riverpod我需要寫一些類似的東西
final profileProvider = StateNotifierProvider((ref) => ProfileState());
class ProfileState extends StateNotifier<ProfileModel> {
ProfileState() : super(null);
}
我知道我需要將ProfileState.empty()
類的東西傳遞給super()
方法而不是傳遞null
但在這種情況下,我必須為每個ProfileModel
字段創建默認值
這對我來說聽起來很奇怪,我不想打破我的頭腦去關心項目中每個模型的空或默認狀態
在我的示例中,用戶名、年齡等沒有默認值
這是純粹的不可變類
我做錯了什么或錯過了什么?
或者我可以將模型聲明為可空extends StateNotifier<ProfileModel?>
但我不確定這是不是一個好方法
可以將StateNotifier
與可為空模型一起使用。 如果您在語義上想表明該值實際上可能不存在,我會說擁有null
是可以的。
但是,我通常做的並且我認為更好的是創建一個包含模型的狀態模型,以及與應用程序可能處於的不同狀態相關的屬性。
例如,在從 API 獲取模型數據時,您可能希望在等待獲取數據的同時在 UI 中顯示加載狀態以顯示微調器。 我寫了一篇關於我使用 Riverpod 應用的架構的文章。
狀態模型的一個簡單示例是:
class ProfileState {
final ProfileModel? profileData;
final bool isLoading;
ProfileState({
this.profileData,
this.isLoading = false,
});
factory ProfileState.loading() => ProfileState(isLoading: true);
ProfileState copyWith({
ProfileModel? profileData,
bool? isLoading,
}) {
return ProfileState(
profileData: profileData ?? this.profileData,
isLoading: isLoading ?? this.isLoading,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is ProfileState &&
other.profileData == profileData &&
other.isLoading == isLoading;
}
@override
int get hashCode => profileData.hashCode ^ isLoading.hashCode;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.