【问题标题】:ListView isnt updating state after I added a FutureBuilder添加 FutureBuilder 后 ListView 未更新状态
【发布时间】: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,
  ),
);
   }

  }

先谢谢了,希望有人能帮助我:)

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    据我所知,您的 _deleteTodo 已从本地实例列表 todos 中删除,但您指示颤振通过 loadData 从磁盘重建 UI,该 UI 从磁盘重新获取数据。

    我的建议是在页面加载时使用initState 获取数据,然后仅引用todos 的本地实例。

    在您的_deleteTodo 中,您还需要将状态保存到磁盘或在某处有一个提交按钮

    【讨论】:

      【解决方案2】:

      我找到了解决方案,在我的 _toggleTodo 中,我需要它来在对我的待办事项执行某些操作后保存我的 TodoList。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-10
        • 2020-01-17
        • 2021-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        相关资源
        最近更新 更多