问题描述
我仍在努力将iconData保存到待办事项应用程序的设备存储中,但出现此错误:
将对象转换为可编码对象失败:“ IconData”的实例
在调试控制台中添加待办事项。
如果我取出iconData,则“待办事项”项已正确保存,当我将其放回时,会收到该错误。
import 'package:Flutter/foundation.dart';
class Todo{
final String id;
final String title;
final IconData icon;
const Todo({
@required this.id,@required this.title,@required this.icon,});
Category.fromMap(
Map map,) :
this.id = map['id'],this.title = map['title'],this.icon = map['icon'],Map toMap() {
return {
'id': this.id,'title': this.title,'icon': this.icon,};
}
}
在我的主脚本中,
List<Todo> _userTodo = List<Todo>();
SharedPreferences sharedPreferences;
@override
void initState() {
initSharedPreferences();
super.initState();
}
initSharedPreferences() async {
sharedPreferences = await SharedPreferences.getInstance();
loadDataTodo();
}
void saveDataTodo() {
List<String> spList = _userTodo
.map((todo) => json.encode(todo.toMap()))
.toList();
sharedPreferences.setStringList(todo,spList);
}
void loadDataTodo() {
List<String> spList = sharedPreferences.getStringList(todo);
_userTodo = spList
.map((todo) => todo.fromMap(json.decode(todo)))
.toList();
setState(() {});
}
请帮助我-我是新来的人
解决方法
IconData
的需求
-
int codePoint;
-
String fontFamily;
-
String fontPackage;
-
bool matchTextDirection;
您可以将它们保存到存储中,并用于(重新)创建IconData。
赞:
Category.fromMap(
Map map,) :
this.id = map['id'],this.title = map['title'],this.icon = IconData(icon: map['codePoint'],fontFamily: map['fontFamily'],fontPackage: map['fontPackage'],matchTextDirection: map['matchTextDirection'],),Map toMap() {
return {
'id': this.id,'title': this.title,'codePoint': this.icon.codePoint,'fontFamily': this.icon.fontFamily,'fontPackage': this.icon.fontPackage,'matchTextDirection': this.icon.matchTextDirection,};
}
,
我建议您通过抖动使用localstorage pkg,而不要对图标数据使用sharedPreferences。