【发布时间】:2019-10-07 05:52:14
【问题描述】:
在此问题发生之前,我正在处理 Future 处理以返回我保存在 sharedPreference 上的值,但是我的 _deleteTodo 方法工作得很好。 在我添加了 FutureBuilder 并最终在 UI 上呈现了我的值之后,现在我正在努力解决这个新错误。 每次我更新状态和项目时,我的 UI 都会反映它,但会立即撤消它
我试图查看它是否与我的 _deleteTodo 方法有关,因此我将 setState 更改为仅将布尔值从 false 更改为 true,但它的作用完全相同。 我还在 _deleteTodo 之后打印了我的列表的长度,并且发生了一些有趣的事情:它工作了一次,_deleteTodo 删除了 Todo,但之后它就不再工作了
This is my TODO class
class Todo {
Todo ({this.title,this.isDone = false});
String title;
bool isDone;
//Decode method to convert a Json String into a Dynamic object
Todo.fromJson(Map <String, dynamic> json)
: title = json ["title"],
isDone = json ["isDone"];
Map <String,dynamic> toJson() =>
{
"title" : title,
"isDone" : isDone
};
}
这是我的屏幕
class _TodoListScreenState extends State<TodoListScreen> {
List<Todo> todos = [];
//updates the state of the checkbox and reflects it on the UI
_toggleTodo(Todo todo, bool isChecked) {
setState(() {
todo.isDone = isChecked;
_deleteTodo(todo,isChecked);
print(todos.length);
});
}
_addTodo() async {
final todo = await showDialog<Todo>(
context: context,
builder: (BuildContext context) { // <- Here you draw the
Dialog
return NewTodoDialog();
},
);
if (todo != null) {
setState(() {
todos.add(todo);
_saveTodo(todos);
print(todos.length);
});
}
}
_deleteTodo (Todo todo, bool isDone) => (isDone)?
todos.remove(todo): debugPrint;
//Save you array object as an array of Strings in Shared Preferences
Future<void> _saveTodo(List<Todo> todo) async {
SharedPreferences sharedPreferences = await
SharedPreferences.getInstance();
sharedPreferences.setStringList("savedData", _mapTodoData(todo));
}
_mapTodoData(List<dynamic> todos) {
try {
var res = todos.map((v) => json.encode(v)).toList();
return res;
} catch (err) {
// Just in case
return ["Nope"];
}
}
Future<List> loadData() async {
SharedPreferences sharedPreferences = await
SharedPreferences.getInstance();
final List<Todo> todoArray =
_decodeTodoData(sharedPreferences.
getStringList("savedData")).toList();
todos = todoArray;
return todoArray;
}
List<Todo> _decodeTodoData(List<String> todos) {
try {
//Transforming List<String> to Json
var result = todos.map((v) => json.decode(v)).toList();
//Transforming the Json into Array<Todo>
var todObjects = result.map((v) => Todo.fromJson(v)).toList();
return todObjects;
} catch (error) {
return [];
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor: Colors.deepPurple[900],
title: Text('Todo List')),
body: Container(
child: FutureBuilder(
future: loadData(),
builder: (BuildContext context, AsyncSnapshot snapshot){
return TodoList(
todos: todos,
onTodoToggle: _toggleTodo,
);
})
)
,
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.purpleAccent[700],
child: Icon(Icons.add),
onPressed: _addTodo,
),
);
}
}
先谢谢了,希望有人能帮助我:)
【问题讨论】: