contacts_dataist_ir/lib/screens/contact_list_screen.dart

137 lines
4.4 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:contacts_dataist_ir/models/contact.dart';
import 'package:contacts_dataist_ir/database/database_helper.dart';
import 'package:contacts_dataist_ir/screens/add_edit_contact_screen.dart'; // Ensure this import is here
class ContactListScreen extends StatefulWidget {
const ContactListScreen({super.key});
@override
State<ContactListScreen> createState() => _ContactListScreenState();
}
class _ContactListScreenState extends State<ContactListScreen> {
final DatabaseHelper _dbHelper = DatabaseHelper();
List<Contact> _contacts = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadContacts();
}
Future<void> _loadContacts() async {
setState(() {
_isLoading = true;
});
try {
final contacts = await _dbHelper.getContacts();
setState(() {
_contacts = contacts;
});
} catch (e) {
if (kDebugMode) {
print('Error loading contacts: $e');
}
} finally {
setState(() {
_isLoading = false;
});
}
}
void _navigateToAddEditContact({Contact? contact}) async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddEditContactScreen(contact: contact),
),
);
if (result == true) {
_loadContacts();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Contacts Dataist IR'),
backgroundColor: Theme.of(context).colorScheme.primary,
),
body:
_isLoading
? const Center(child: CircularProgressIndicator())
: _contacts.isEmpty
? const Center(
child: Text(
'No contacts found. Add a new one!',
style: TextStyle(fontSize: 18),
),
)
: ListView.builder(
itemCount: _contacts.length,
itemBuilder: (context, index) {
final contact = _contacts[index];
return Card(
margin: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 5,
),
child: ListTile(
title: Text(contact.name),
subtitle: Text(
contact.phone ?? contact.email ?? 'No phone or email',
),
onTap: () {
_navigateToAddEditContact(contact: contact);
},
trailing: IconButton(
icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () async {
final confirm = await showDialog<bool>(
context: context,
builder:
(context) => AlertDialog(
title: const Text('Delete Contact'),
content: Text(
'Are you sure you want to delete ${contact.name}?',
),
actions: [
TextButton(
onPressed:
() => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed:
() => Navigator.pop(context, true),
child: const Text('Delete'),
),
],
),
);
if (confirm == true) {
await _dbHelper.deleteContact(contact.id!);
_loadContacts();
}
},
),
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_navigateToAddEditContact();
},
child: const Icon(Icons.add),
),
);
}
}