首页 > 解决方案 > 在颤动中将图标保存到共享首选项

问题描述

我仍在努力将 iconData 保存到我的待办事项应用程序的设备存储中,我收到此错误:

将对象转换为可编码对象失败:“IconData”实例

在调试控制台中添加待办事项。

如果我取出 iconData,To-Do 项目正在正确保存,当我把它放回去时,我得到了那个错误。

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(() {});
  }

请帮助我 - 我是新来的颤振

标签: flutterdart

解决方案


除非您这样做,否则 loadDataTodo 中的 setState 不会做太多事情:

void loadDataTodo() {
    List<String> spList = sharedPreferences.getStringList(todo);
    setState(() {
       _userTodo = spList
        .map((todo) => todo.fromMap(json.decode(todo)))
        .toList();
    });
  }

尝试打印 _userTodo 并检查此更改后它是否为空。

sharedPreferences.setStringList(todo, spList) //todo should be a string.

推荐阅读