import 'package:flutter/material.dart'; import 'package:flutter_contacts/flutter_contacts.dart'; // Updated package class ContactPage extends StatefulWidget { const ContactPage({super.key}); @override _ContactPageState createState() => _ContactPageState(); } class _ContactPageState extends State { List _contacts = []; bool _loading = true; @override void initState() { super.initState(); _fetchContacts(); } // Request permission and fetch contacts Future _fetchContacts() async { if (await FlutterContacts.requestPermission()) { List contacts = await FlutterContacts.getContacts(withProperties: true, withThumbnail: true); setState(() { _contacts = contacts; _loading = false; }); } else { setState(() { _loading = false; }); } } // Add a new contact using flutter_contacts Future _addNewContact() async { Contact newContact = Contact( name: Name(first: 'John', last: 'Doe'), phones: [Phone('123456789')], ); await FlutterContacts.insertContact(newContact); _fetchContacts(); // Refresh the contact list } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Contacts'), ), body: _loading ? const Center(child: CircularProgressIndicator()) : _contacts.isEmpty ? const Center(child: Text('No contacts found')) : ListView.builder( itemCount: _contacts.length, itemBuilder: (context, index) { return ContactTile(contact: _contacts[index]); }, ), floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: _addNewContact, ), ); } } // Contact Tile to display each contact class ContactTile extends StatelessWidget { final Contact contact; const ContactTile({super.key, required this.contact}); @override Widget build(BuildContext context) { return ListTile( leading: (contact.thumbnail != null) ? CircleAvatar(backgroundImage: MemoryImage(contact.thumbnail!)) : CircleAvatar(child: Text(_getInitials(contact.displayName))), title: Text(contact.displayName ?? 'No Name'), subtitle: contact.phones.isNotEmpty ? Text(contact.phones.first.number) : const Text('No phone number'), trailing: IconButton( icon: const Icon(Icons.call), onPressed: () { // Handle call action }, ), ); } String _getInitials(String? name) { if (name == null || name.isEmpty) return ""; List names = name.split(' '); return names.map((n) => n[0]).take(2).join().toUpperCase(); } }