【问题标题】:How to save the state of a checkbox in shared preferences in flutter?如何在颤动中保存共享首选项中的复选框状态?
【发布时间】:2020-11-12 08:53:33
【问题描述】:

我想将复选框小部件的选中状态保存在共享首选项中。 这样当我们再次启动应用程序时,我们应该会看到选中的列表。

这是代码,但它不起作用,因为选中的列表在刷新时变回未选中的列表。

我已经使用 SQLite 数据库来保存 ToDo 列表的详细信息。

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

【问题讨论】:

    标签: sqlite flutter checkbox sharedpreferences state


    【解决方案1】:

    您没有对您在initState() 中调用的getValues() 函数的返回值做任何事情。

    @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. 
    }
    

    我看到您的复选框的值是从列表中设置的,也许将值存储在您的 getValues() 函数中的列表中。

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

    ?? 是一个 null 感知运算符,如果保存的 valnull,它将设置 _todoList[0].isCheckedfalse,如果您还没有保存任何内容,则可能发生这种情况。

    【讨论】:

    • 如果它解决了您的问题,请将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2016-12-26
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多