I am still struggling to save an iconData to the devices storage for my to-do app, I get this error:
Converting object to an encodable object failed: Instance of 'IconData'
in the debug console while adding the to-do item.
If I take out the iconData, the To-Do item is saving correctly, and when I put it back in, I get that error.
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,
};
}
}
and in my main script I have
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(() {});
}
Please help me - I am new to flutter
Solution 1: krumpli
setState in loadDataTodo isn't doing much unless you do this:
void loadDataTodo() {
List<String> spList = sharedPreferences.getStringList(todo);
setState(() {
_userTodo = spList
.map((todo) => todo.fromMap(json.decode(todo)))
.toList();
});
}
Try printing _userTodo and check if it's empty after this change.
sharedPreferences.setStringList(todo, spList) //todo should be a string.