Я делаю приложение todo с firebase для практики. Я хочу поставить опцию, чтобы создать категорию, а затем создать под нее задачи. Когда кто-то добавляет категорию, я сделал задачу без субъекта (null), тогда я могу проверить, является ли тема пустым или нет для элемента todo сборки. Затем я создаю контрольный список, чтобы избежать повторяющихся построений категорий в просмотре списка. Это работает хорошо, я могу добавить категорию без показа каких-либо задач, я могу добавить задачу в любую категорию, и они показали правильно, я могу проверять или удалять задачи без каких-либо проблем, но когда я попытался удалить карточку категории, которую он удаляет из базы данных со всеми связанными задачами, без каких-либо проблем, но в пользовательском интерфейсе он все еще остается там, пока я не попытался удалить несколько раз, после чего он исчез. Я пытался удалить его из контрольного списка (вы можете увидеть в коде), но все равно он не работает. Я думаю, что
Моя модель todo такая:
class Todo {
String key;
String subject;
bool completed;
String userId;
String category;
int timeStamp;
Todo(
this.subject,
this.userId,
this.completed,
this.category,
);
Todo.fromSnapshot(DataSnapshot snapshot) :
key = snapshot.key,
userId = snapshot.value["userId"],
subject = snapshot.value["subject"],
completed = snapshot.value["completed"],
category = snapshot.value["category"],
timeStamp = snapshot.value['timeStamp'];
toJson() {
return {
"userId": userId,
"subject": subject,
"completed": completed,
"category": category,
"timeStamp" : DateTime.now().microsecondsSinceEpoch.toInt(),
};
}
}
Основы c build logi c моего кода ниже;
List<Todo> _todoList;
Query _todoQuery;
...
void initState() {
//_checkEmailVerification();
_calendarController = CalendarController();
_todoList = new List();
_todoQuery = _database
.reference()
.child("todo").child(widget.userId)
.orderByChild("userId")
.equalTo(widget.userId);
_onTodoAddedSubscription = _todoQuery.onChildAdded.listen(onEntryAdded);
_onTodoChangedSubscription =
_todoQuery.onChildChanged.listen(onEntryChanged);
super.initState();
}
...
Widget build(BuildContext context) {
_textEditingController.clear();
var checklist = [];
var openList = [];
for(var i = 0; i < checklist.length; i++) {
if(openList == null)
openList.add(false);
}
for(var i in _todoList){
if(!checklist.contains(i.category))
checklist.add(i.category);
}
var subjectList = [];
for(var i in _todoList){
if(!subjectList.contains(i.subject))
subjectList.add(i.subject);
}
return new Scaffold(
appBar: new AppBar(
title: new Text('My Cute ToDo App'),
actions: <Widget>[
new FlatButton(
child: new Text('Logout',
style: new TextStyle(fontSize: 17.0, color: Colors.white)),
onPressed: signOut)
],
),
body: Container(
child: Column(
children: <Widget>[
checklist != null ?
Container(
child: Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: checklist.length,
itemBuilder: (BuildContext context, int indexC) {
return
Container(
child: Column(
children: <Widget>[
Dismissible(
key: UniqueKey(),
background: Container(color: Colors.red),
onDismissed: (direction) async {
FirebaseDatabase.instance.reference()
.child('todo').child(widget.userId)
.orderByChild('category')
.equalTo(checklist[indexC])
.once()
.then((DataSnapshot snapshot) {
Map<dynamic, dynamic> children = snapshot.value;
children.forEach((key, value) {
FirebaseDatabase.instance.reference()
.child('todo').child(widget.userId)
.child(key)
.remove();
});
});
checklist.remove(checklist[indexC]);
setState(() {
_todoList.removeAt(indexC);
});
},
child: Card(
elevation: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
FlatButton(
onPressed: (){openList[indexC] = !openList[indexC];
setState(() {
});},
child: Text(checklist[indexC], style: TextStyle(fontSize: 20),)
),
],
),
FlatButton(
child: Icon(Icons.add_circle),
onPressed: () {
showAddTodo(context, indexC);
}
),
]
),
),
),
AnimatedClipRect(
open: true,
horizontalAnimation: false,
verticalAnimation: true,
alignment: Alignment.center,
duration: Duration(milliseconds: 1000),
curve: Curves.bounceOut,
reverseCurve: Curves.bounceIn,
child: ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: _todoList.length,
itemBuilder: (BuildContext context, int index) {
String todoId = _todoList[index].key;
String subject = _todoList[index].subject;
bool completed = _todoList[index].completed;
String category = _todoList[index].category;
return subject != null && category == checklist[indexC] ?
Dismissible(
key: Key(todoId),
background: Container(color: Colors.red),
onDismissed: (direction) async {
deleteTodo(todoId, index);
},
child:
subject != null ?
ListTile(
title: Text(
subject,
style: TextStyle(fontSize: 18.0),
),
trailing: IconButton(
icon: (completed)
? Icon(
Icons.done_outline,
color: Colors.green,
size: 20.0,
)
: Icon(Icons.done, color: Colors.grey, size: 20.0),
onPressed: () {
updateTodo(_todoList[index]);
}),
) : Row()
) : Row();
})),
]),
);
}),
),
)
: Container()
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showAddTodoCategory(context);},
tooltip: 'Category',
child: Icon(Icons.category),));
}