monorepo/dialer/lib/features/contacts/widgets/alphabet_scroll_page.dart

323 lines
12 KiB
Dart

import 'package:dialer/widgets/username_color_generator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import '../../../widgets/color_darkener.dart';
import '../contact_state.dart';
import 'add_contact_button.dart';
import 'contact_modal.dart';
import 'share_own_qr.dart';
class AlphabetScrollPage extends StatefulWidget {
final List<Contact> contacts;
final double scrollOffset;
const AlphabetScrollPage(
{super.key, required this.contacts, required this.scrollOffset});
@override
_AlphabetScrollPageState createState() => _AlphabetScrollPageState();
}
class _AlphabetScrollPageState extends State<AlphabetScrollPage> {
late ScrollController _scrollController;
List<Contact> _contacts = []; // Local copy of contacts for updating
@override
void initState() {
super.initState();
_contacts = widget.contacts; // Initialize with the provided contacts
_scrollController =
ScrollController(initialScrollOffset: widget.scrollOffset);
_scrollController.addListener(_onScroll);
}
void _onScroll() {
final contactState = ContactState.of(context);
contactState.setScrollOffset(_scrollController.offset);
}
Future<void> _refreshContacts() async {
if (await FlutterContacts.requestPermission()) {
final updatedContacts = await FlutterContacts.getContacts(
withProperties: true, withThumbnail: true);
setState(() {
_contacts = updatedContacts;
});
}
}
// void _toggleFavorite(Contact contact) async {
// print(contact.id);
// if (await FlutterContacts.requestPermission()) {
// try {
// // Fetch all contacts (this can be slow if there are many contacts)
// List<Contact> allContacts = await FlutterContacts.getContacts(
// withProperties: true,
// withThumbnail: true,
// withAccounts: true,
// withPhoto: true
// );
// // Find the specific contact by matching contact.id
// // Use `orElse` to return a nullable Contact? or throw an exception if not found
// Contact? contactToUpdate = allContacts.firstWhere(
// (c) => c.id == contact.id,
// orElse: () => throw Exception(
// "Contact not found"), // Throw an exception if not found
// );
// if (contactToUpdate != null) {
// print("Contact fetched: ${contactToUpdate.displayName}");
// print("Current isStarred status: ${contactToUpdate.isStarred}");
// // Toggle the favorite status
// contactToUpdate.isStarred = !contactToUpdate.isStarred;
// print("Updated isStarred status: ${contactToUpdate.isStarred}");
// // Update the contact
// await FlutterContacts.updateContact(contactToUpdate);
// print("Contact updated successfully");
// // Refresh the UI by updating the state
// setState(() {
// contact.isStarred = contactToUpdate.isStarred;
// });
// }
// } catch (e) {
// print("Error updating favorite status: $e");
// }
// }
// }
// void _toggleFavorite(Contact contact) async {
// print(contact.id);
// try {
// // Fetch the contact with details
// final contactWithDetails = await FlutterContacts.getContact(contact.id,
// withProperties: true, withThumbnail: true, withAccounts: true);
// if (contactWithDetails != null) {
// print("Contact fetched: ${contactWithDetails.displayName}");
// print("Current isStarred status: ${contactWithDetails.isStarred}");
// // Toggle the favorite status
// contactWithDetails.isStarred = !contactWithDetails.isStarred;
// print("Updated isStarred status: ${contactWithDetails.isStarred}");
// // Update the contact
// await FlutterContacts.updateContact(contactWithDetails);
// print("Contact updated successfully");
// // Reset the contact state (optional)
// setState(() {
// contact.isStarred = contactWithDetails.isStarred;
// });
// // Re-fetch the contact to ensure UI reflects changes
// final updatedContact = await FlutterContacts.getContact(contact.id,
// withProperties: true, withThumbnail: true, withAccounts: true);
// if (updatedContact != null) {
// print("Re-fetched updated contact: ${updatedContact.displayName}");
// print("Re-fetched isStarred status: ${updatedContact.isStarred}");
// } else {
// print("Re-fetching contact failed.");
// }
// } else {
// print("Contact details are not available");
// }
// } catch (e) {
// print("Error updating favorite status: $e");
// }
// }
void _toggleFavorite(Contact contact) async {
print(contact.id);
try {
if (contact != null) {
print("Contact fetched: ${contact.displayName}");
print("Current isStarred status: ${contact.isStarred}");
// Toggle the favorite status
contact.isStarred = !contact.isStarred;
print("Updated isStarred status: ${contact.isStarred}");
// Update the contact
await FlutterContacts.updateContact(contact);
print("Contact updated successfully");
// Reset the contact state (optional)
setState(() {
contact.isStarred = contact.isStarred;
});
// Re-fetch the contact to ensure UI reflects changes
final updatedContact = await FlutterContacts.getContact(contact.id,
withProperties: true, withThumbnail: true, withAccounts: true);
if (updatedContact != null) {
print("Re-fetched updated contact: ${updatedContact.displayName}");
print("Re-fetched isStarred status: ${updatedContact.isStarred}");
} else {
print("Re-fetching contact failed.");
}
} else {
print("Contact details are not available");
}
} catch (e) {
print("Error updating favorite status: $e");
}
}
@override
Widget build(BuildContext context) {
Map<String, List<Contact>> alphabetizedContacts = {};
for (var contact in _contacts) {
String firstLetter = contact.displayName.isNotEmpty
? contact.displayName[0].toUpperCase()
: '#';
if (!alphabetizedContacts.containsKey(firstLetter)) {
alphabetizedContacts[firstLetter] = [];
}
alphabetizedContacts[firstLetter]!.add(contact);
}
List<String> alphabetKeys = alphabetizedContacts.keys.toList()..sort();
return Scaffold(
backgroundColor: Colors.black,
body: Column(
children: [
// Top buttons row
Container(
color: Colors.black,
padding:
const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
AddContactButton(),
QRCodeButton(
contacts: _contacts,
selfContact: ContactState.of(context).selfContact),
],
),
),
// Contact List
Expanded(
child: ListView.builder(
controller: _scrollController,
itemCount: alphabetKeys.length,
itemBuilder: (context, index) {
String letter = alphabetKeys[index];
List<Contact> contacts = alphabetizedContacts[letter]!;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Alphabet Letter Header
Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0, horizontal: 16.0),
child: Text(
letter,
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
// Contact Entries
...contacts.map((contact) {
String phoneNumber = contact.phones.isNotEmpty
? contact.phones.first.number
: 'No phone number';
Color avatarColor =
generateColorFromName(contact.displayName);
return ListTile(
leading: (contact.thumbnail != null &&
contact.thumbnail!.isNotEmpty)
? CircleAvatar(
backgroundImage:
MemoryImage(contact.thumbnail!),
)
: CircleAvatar(
backgroundColor: avatarColor,
child: Text(
contact.displayName.isNotEmpty
? contact.displayName[0].toUpperCase()
: '?',
style: TextStyle(
color: darken(avatarColor, 0.4)),
),
),
title: Text(contact.displayName,
style: TextStyle(color: Colors.white)),
subtitle: Text(phoneNumber,
style: TextStyle(color: Colors.white70)),
onTap: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) {
return ContactModal(
contact: contact,
onEdit: () async {
// Trigger edit logic and refresh contacts
if (await FlutterContacts
.requestPermission()) {
final updatedContact =
await FlutterContacts.openExternalEdit(
contact.id);
if (updatedContact != null) {
await _refreshContacts();
Navigator.of(context).pop();
ScaffoldMessenger.of(context)
.showSnackBar(
SnackBar(
content: Text(
'${contact.displayName} updated successfully!'),
),
);
} else {
ScaffoldMessenger.of(context)
.showSnackBar(
SnackBar(
content:
Text('Edit canceled or failed.'),
),
);
}
}
},
onToggleFavorite: () {
_toggleFavorite(contact);
},
isFavorite: contact.isStarred,
);
},
);
},
);
}),
],
);
},
),
),
],
),
);
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
}