mercredi 22 juillet 2020

How to save the state of a checkbox in shared preferences in flutter?

I want to save the checked state of checkbox widget in the shared preference. So that when we start the app again then we should see the checked list.

Here is the code but it's not working as in the checked list changes back to unchecked list on refresh.

I have used SQLite database to save the ToDo list details.

class _HomeState extends State<Home> {

  TodoService _todoService;
  var _selectedValue;
  var _categories = List<DropdownMenuItem>();

  List<Todo>_todoList=List<Todo>();
  final GlobalKey<ScaffoldState> _globalKey=GlobalKey<ScaffoldState>();




  @override
  initState(){
    super.initState();
    getAllTodos();
    _loadCategories();
    getValues();
  }


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


  _save(String key,dynamic val)async{
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(key,val);
  }
  getValues() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    bool value=prefs.getBool('Checked');
    return value;
  }

      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: ListTile(
                leading: Checkbox(
                  checkColor: Colors.indigo,
                  value: _todoList[index].isChecked,
                  onChanged:(bool value){
                      setState(() {
                        _todoList[index].isChecked=value;


                      });
                      _save('Checked',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'),
//                  trailing: Text(_todoList[index].dueDate ?? 'No Due Date'),
              ),
          ),
        );
      }),
      floatingActionButton: FloatingActionButton(
        onPressed: ()=>Navigator.of(context).push(MaterialPageRoute(builder:(context)=>TodoScreen())),
        child: Icon(Icons.add),
      ),
    );
  }
} 



Aucun commentaire:

Enregistrer un commentaire