I'm building a todo app in which CRUD operations can be carried out. With the help of Sqlflite todo items will be stored/retrieved from the database. When i try to delete todos, it works just as fine except the last item in the list view remains even after deleting it from the database. But, once the app restarts the last item gets removed. Tried setState() manually to refresh the page but nothings works. Help me sort this out and thanks in adavance.
//Holds the todos and will be passed to ListView.builder
List<Todo> listOfValues;
//Holds the indexes of selected items to highlight the items in the ListView
List<int> indexes = [];
//Holds the ids of selected items to perform CRUD
List<int> selectedItems = [];
//This is where the todos are retrieved from the database.
//Following DatabaseModel is a database helper class
DatabaseModel data = DatabaseModel();
data.queryingData().then((value) {
setState(() {
if (value.isNotEmpty) {
listOfValues = value;
}
});
});
Following block builds/returns the body of the main page of the app which is a ListView contains todos.
Widget content() {
return SafeArea(
child: Container(
child: ListView.builder(
itemBuilder: (context, index) {
return Card(
color: (indexes.contains(index))
? Colors.blue.withOpacity(0.5)
: Colors.transparent,
child: ListTile(
title: Text(listOfValues[index].todo),
subtitle: Text('Planned on ${listOfValues[index].date}'),
trailing: Text(listOfValues[index].time),
onLongPress: () {
setState(() {
lonPressEnabled = true;
if (!indexes.contains(index)) {
indexes.add(index);
selectedItems.add(listOfValues[index].id);
}
});
},
onTap: () {
setState(() {
if (indexes.isNotEmpty && lonPressEnabled) {
if (indexes.contains(index)) {
indexes.remove(index);
selectedItems.remove(listOfValues[index].id);
} else {
indexes.add(index);
selectedItems.add(listOfValues[index].id);
}
}
});
},
),
);
},
itemCount: listOfValues.length,
),
),
);}
Following block is used to delete items from database
ElevatedButton(
onPressed: () {
lonPressEnabled = false;
DatabaseModel model = DatabaseModel();
for (int i = 0; i < selectedItems.length; i++) {
model.deletingRecord(selectedItems[i]);
//selectedItems holds the ids of each todos
}
selectedItems = [];
indexes = [];
setState(() {
print();
});
},
child: const Icon(Icons.delete));
Following block deletes todo from the database
deletingRecord(int ids) async {
Database db = await openingDB;
db.rawDelete('delete from ToDos where id=$ids');}