【发布时间】: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