I want to fetch my conatct list to my flutter application, I want name and number, I tried but in screen it not visible but backend Terminal i am getting all the contacts list and I contacts is displaying twice in the terminal, Please check the code and guide and help how can i display my all contacts list in flutter application.
class ContactsPage extends StatefulWidget {
@override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
var _contacts = [];
@override
void initState() {
super.initState();
_contacts = getContacts();
}
getContacts() async {
Iterable<Contact> contacts = await ContactsService.getContacts();
for (var contact in contacts) {
print('Name: ${contact.displayName }');
print('Phone number: ${contact.phones!.isNotEmpty }');
// Add more fields as needed
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Contacts List'),
),
body:
ListView.builder(
itemCount: _contacts.length,
itemBuilder: (context, index) {
Contact contact = _contacts[index];
List<Item> phoneNumbers = contact.phones!.toList();
return Column(
children: [
ListTile(
title: Text(' ${contact.displayName }'),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: phoneNumbers.map((Item phoneNumber) {
return Text('${contact.phones!.isNotEmpty ? contact.phones!.first.value : ' '}');
}).toList(),
),
),
],
);
},
),
);
}
}
so many detail you have to check.
1. You have to check the permission first.
I'm using Permission Handler to check the permission, is it granted or no.
2. You have to use the FutureBuilder of other State Management.
Here i'm using FutureBuilder because the ContactService package need some time to fetch all contact from native. The response could be null or another error. You need to check the condition first.
Here my pubspec.yaml