how to fetch my device all contacts list to my flutter application

1.5k Views Asked by At

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(),
         ),
         ),
        ],
      );
    },
   ),
  );
 }
}
1

There are 1 best solutions below

0
Anan Alfred On

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.

import 'package:contacts_service/contacts_service.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

class ContactsPage extends StatefulWidget {
  const ContactsPage({super.key});

  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> { 
  @override
  void initState() {
    super.initState();
    _askPermissions();
  }

  Future<void> _askPermissions() async {
    PermissionStatus permissionStatus = await _getContactPermission();
    if (permissionStatus != PermissionStatus.granted) {
      _handleInvalidPermissions(permissionStatus);
    }
  }

  Future<PermissionStatus> _getContactPermission() async {
    PermissionStatus permission = await Permission.contacts.status;
    if (permission != PermissionStatus.granted &&
        permission != PermissionStatus.permanentlyDenied) {
      PermissionStatus permissionStatus = await Permission.contacts.request();
      return permissionStatus;
    } else {
      return permission;
    }
  }

  void _handleInvalidPermissions(PermissionStatus permissionStatus) {
    if (permissionStatus == PermissionStatus.denied) {
      const snackBar = SnackBar(content: Text('Access to contact data denied'));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    } else if (permissionStatus == PermissionStatus.permanentlyDenied) {
      const snackBar =
          SnackBar(content: Text('Contact data not available on device'));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    }
  }

  Future<List<Contact>>? reqContact;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Contacts List'),
      ),
      body: Column(
        children: [
          ElevatedButton(
              onPressed: () {
                setState(() {
                  reqContact = ContactsService.getContacts();
                });
              },
              child: const Text("Load Contact")),
          Expanded(
              child: FutureBuilder(
                  future: reqContact,
                  builder: (context, snp) {
                    if (snp.connectionState == ConnectionState.done) {
                      var contacts = snp.data;

                      if (contacts != null) {
                        return ListView.builder(
                            shrinkWrap: true,
                            itemCount: contacts.length,
                            itemBuilder: (context, index) {
                              Contact contact = contacts[index];

                              return ListTile(
                                  title: Text(' ${contact.displayName}'),
                                  subtitle: Text(contact.phones?.single.value ??
                                      "not found"));
                            });
                      }
                      return Container();
                    }
                    return Container();
                  })),
        ],
      ),
    );
  }
}

Here my pubspec.yaml enter image description here