cpd/lib/widgets/listview.dart

110 lines
3.6 KiB
Dart
Raw Normal View History

2024-05-09 09:46:23 +02:00
import 'package:flutter/material.dart';
import 'package:cpd/database/habit.dart';
import 'package:cpd/widgets/edithabit_dialog.dart';
import '../database/todo_interface.dart';
class MyListView extends StatefulWidget {
final List<Habit> habits;
final ToDoInterface todoDB;
final Function fetchTodos;
final Function(int) updateCounter;
const MyListView({
super.key,
required this.habits,
required this.todoDB,
required this.fetchTodos,
required this.updateCounter,
});
@override
MyListViewState createState() => MyListViewState();
}
class MyListViewState extends State<MyListView> {
2024-05-09 09:46:23 +02:00
@override
Widget build(BuildContext context) {
int completedCount = widget.habits.where((habit) => habit.isComplete).length;
2024-05-09 09:46:23 +02:00
return ListView.builder(
shrinkWrap: true,
padding: EdgeInsets.zero,
itemCount: widget.habits.length,
2024-05-09 09:46:23 +02:00
itemBuilder: (BuildContext context, int index) {
final todo = widget.habits[index];
String newTitle = todo.title;
String? newSubtitle = todo.subtitle;
IconData newIcon = todo.icon;
2024-05-09 09:46:23 +02:00
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: Card(
color: index % 2 == 0 ? Colors.green[300] : Colors.green[100],
child: Dismissible(
key: Key(widget.habits[index].title),
2024-05-09 09:46:23 +02:00
background: Container(
color: Colors.blue,
2024-05-09 09:46:23 +02:00
alignment: Alignment.centerLeft,
child: const Padding(
padding: EdgeInsets.only(left: 16),
child: Icon(Icons.edit),
),
),
secondaryBackground: Container(
color: Colors.red,
alignment: Alignment.centerRight,
child: const Padding(
padding: EdgeInsets.only(right: 16),
child: Icon(Icons.delete),
2024-05-09 09:46:23 +02:00
),
),
onDismissed: (direction) async {
// Löschen
if (direction == DismissDirection.endToStart) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("${widget.habits[index].title} was dismissed"))
);
await widget.todoDB.delete(todo.id);
widget.fetchTodos();
}
// Bearbeiten
else if (direction == DismissDirection.startToEnd) {
showDialog(
context: context,
builder: (context) => EditHabitDialog(
todo: todo,
todoDB: widget.todoDB,
fetchTodos: widget.fetchTodos,
)
);
}
setState(() {
widget.habits.removeAt(index);
});
2024-05-09 09:46:23 +02:00
},
child: ListTile(
title: Text(newTitle),
subtitle: Text(newSubtitle),
trailing: Icon(newIcon),
2024-05-09 09:46:23 +02:00
leading: Checkbox(
value: todo.isComplete,
2024-05-09 09:46:23 +02:00
onChanged: (value) {
if (value != null) {
widget.todoDB.updateCompletionStatus(todo.id, value);
widget.fetchTodos();
setState(() {
completedCount += value ? 1 : -1;
});
widget.updateCounter(completedCount);
}
},
2024-05-09 09:46:23 +02:00
),
),
),
),
);
},
2024-05-09 09:46:23 +02:00
);
}
}