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

759

You're not doing anything with the returned value from the getValues() function you call in initState().

@override
initState(){
  super.initState();
  getAllTodos();
  _loadCategories();
  getValues(); // This is returning the saved value, either true, false, or null. You must set your checkBox initially to this value. 
}

I see that your checkbox has its value set from a list, perhaps store the value in the list in your getValues() function.

getValues() async {
   final SharedPreferences prefs = await SharedPreferences.getInstance();
   bool val = prefs.getBool('Checked');
   setState(() {
      _todoList[0].isChecked = val?? false;
   });
}

?? is a null-aware operator that will set _todoList[0].isChecked to false if the saved val is null, which can happen if you don't have anything saved yet.

Share:
759
Ruchita Bhaskar
Author by

Ruchita Bhaskar

Updated on December 22, 2022

Comments

  • Ruchita Bhaskar
    Ruchita Bhaskar over 1 year

    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),
          ),
        );
      }
    } 
    
  • SCcode
    SCcode over 3 years
    Please mark this as the answer if it solved your problem.