[英]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.