I am developing an application where I should access the contacts of the user. I am using contacts_service and permission_handler to access the contacts and here is my code:
import 'package:contacts_service/contacts_service.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Contact> contacts = [];
@override
void initState() {
super.initState();
getAllContacts();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: contacts.length,
itemBuilder: (_, i) {
Contact contact = contacts[i];
return ListTile(
title: Text(contact.displayName!),
subtitle: Text(contact.phones!.elementAt(0).value.toString()),
);
}));
}
void getAllContacts() async {
List<Contact> _contacts = await ContactsService.getContacts(withThumbnails: false);
setState(() {
contacts = _contacts;
});
}
}
and I added the lines below to my AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
Problem
I get a range error:
The following RangeError was thrown building:
RangeError (index): Invalid value: Valid value range is empty: 0
If I comment the subtitle
part everything is fine. so the problem is that contact_service can not get the contact phone numbers and I don’t know why.
anyone can help me?
I tried flutter_contacts and I have the same issue with the getContacts
function but getContact
works fine
2
Answers
so at first I switched to flutter_contacts because the getContact for having a specific contact object worked, Although this is a hard way. But I figured that I had to use the
withProperties: true
option. I could not find the same option in contact_service. Everything works with flutter_contacts.first of all don't forget to use the below command on the project directory:
then use this code:
Replace the getAllContacts function with
subtitle with
and replace the import statement from
to
it should work fine with flutter_contacts.