mardi 21 juillet 2020

OnChanged State of Checkbox in Flutter

I am working on todo list app and used CheckBox to check off the todo in the list.

But the keeps going back to unchecked state on refreshing the page. I want to save the state in the database. I am populating the todoList in getAllTodos

Here is the code:

getAllTodos()async{
    _todoService=TodoService();
    _todoList=List<Todo>();

    var todos= await _todoService.readTodo();

    todos.forEach((todo){
      setState(() {
        var model=Todo();
        model.id=todo['id'];
        model.title=todo['title'];
        model.dueDate=todo['dueDate'];
        model.category=todo['category'];
        model.isFinished=todo['isFinished'];
        _todoList.add(model);
      });
    });
  } 

    body: ListView.builder(itemCount: _todoList.length,itemBuilder: (context, index){
            return Padding(
              padding:  EdgeInsets.only(top:8.0, left: 8.0, right: 8.0),
    

      child: Card (
            elevation: 8.0,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(0)
            ),
              child: InkWell(
                onTap: (){
                  setState(() {
                    _todoList[index].isChecked=!_todoList[index].isChecked;
                  });
                },
                child: ListTile(
                  leading: Checkbox(
                    checkColor: Colors.indigo,
                    value: _todoList[index].isChecked,
                    onChanged: (bool value){
                      setState(() {
                        _todoList[index].isChecked=value;
                      });
                    },
                  ),
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(_todoList[index].title ?? 'No Title',
                        style: TextStyle(decoration: (_todoList[index].isChecked? TextDecoration.lineThrough: TextDecoration.none),
                        ),
                      ),
                      IconButton(icon: Icon(Icons.delete,color: Colors.red,
                      ),
                          onPressed: (){
                            _deleteFormDialog(context,_todoList[index].id);
                          }
                      ),
                    ],
                  ),
                  subtitle: Text(_todoList[index].dueDate ?? 'No Due Date'),
                ),
              ),
          ),
        );
      }),

Here is the isChecked value:

class Todo{
  bool isChecked=false; 
}

Please help me out.




Aucun commentaire:

Enregistrer un commentaire