[英]Flutter Hydrated Bloc always replaced with the initial state and not persisting
我正在嘗試使用水合塊來保持我的肘部。
但是經過一番試錯,發現加載的state總是會被初始的state替換
class DefectSectionsCubit extends HydratedCubit<DefectSectionsState> {
DefectSectionsCubit() : super(DefectSectionsState.initial()) {
print("replaced by init");
}
@override
DefectSectionsState? fromJson(Map<String, dynamic> json) {
print("get from json");
return DefectSectionsState.fromMap(json);
}
@override
Map<String, dynamic>? toJson(DefectSectionsState state) {
return state.toMap();
}
}
“從 json 獲取”確實獲取了我之前保存的最后一個 state,但它很快就會被初始的 state 替換,因此 state 無法保留。 output 將是:
I/flutter (30280): get from json
I/flutter (30280): replaced by init
你可以看到 fromJson 將首先被調用,然后是構造函數,這使得初始 state 將始終覆蓋加載的 state。
我的state是這樣的:
class DefectSectionsState extends Equatable {
final List<DefectSection> defectSections;
const DefectSectionsState({
required this.defectSections,
});
factory DefectSectionsState.initial() => const DefectSectionsState(
defectSections: [
DefectSection(
sectionName: 'FABRIC',
defectItems: [
DefectItem(name: 'Cotton'),
],
),
DefectSection(
sectionName: 'COLOR',
defectItems: [
DefectItem(name: 'Crimson'),
],
),
DefectSection(
sectionName: 'SEWING',
defectItems: [
DefectItem(name: 'Lockstitch'),
],
),
],
);
}
那么如何讓我的 state 持久化呢?
謝謝
我在我的 state 中錯誤地實現了fromMap
。
所以,我通過實施適當的fromMap
來解決這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.