Trending Articles       10 Flutter Listview Examples       Flutter Custom Button Example       Flutter Audio Recording       Flutter 2.0 Autocomplete TextField       Current Location Google Maps

How to Access Contacts in Flutter Application (Read and Make Phone calls)

How to get Phone call list and display on Listview in Flutter application.

This post will show how to featch contacts and make phone calls from flutter application.

For this example we are going to use flutter_contact plugin to fetch the contacts from Phone contacts

 

Read Contacts from Phone

 

If you do not already have a Flutter project set up please refer to our introductory Flutter tutorial for details.

 

Getting Started

 

Dependencies

Add required dependenices in pubspec.yaml file

flutter_contact : Read Contacts from Phone

permission_handler : Handle Permissionrequest for Android Marshmallow and above versions

url_launcher : Make phone call from application

flutter_contact: ^0.6.4
permission_handler: ^5.0.1+1
url_launcher: ^5.7.2

 

Add required Permissions

Update manifest file with adding below permisions

<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>

 

iOS Set Up

Add permissions for iOS into the info.plist file

<key>NSAppleMusicUsageDescription</key>
<string>Music!</string>
<key>kTCCServiceMediaLibrary</key>
<string>media</string>
<key>NSCalendarsUsageDescription</key>
<string>Calendars</string>
<key>NSCameraUsageDescription</key>
<string>camera</string>
<key>NSContactsUsageDescription</key>
<string>contacts</string>
<key>NSMicrophoneUsageDescription</key>
<string>microphone</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>speech</string>
<key>NSMotionUsageDescription</key>
<string>motion</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>photos</string>
<key>NSRemindersUsageDescription</key>
<string>reminders</string>

 

Requesting Contacts Permission

To get Contact permission we need to write below code

 

//Check contacts permission
Future<PermissionStatus> _getPermission() async {
  final PermissionStatus permission = await Permission.contacts.status;
  if (permission != PermissionStatus.granted &&
      permission != PermissionStatus.denied) {
    final Map<Permission, PermissionStatus> permissionStatus =
    await [Permission.contacts].request();
    return permissionStatus[Permission.contacts] ??
        PermissionStatus.undetermined;
  } else {
    return permission;
  }
}

 

Read Contacts

We need to write below lines of code to fetch the contacts from Phone contacts

Contacts.streamContacts().forEach((contact) {
  print("${contact.displayName}");

    });

 

Display Contacts inside Listview

Container(

  child:(listContacts.length>0)?ListView.builder(
      itemCount: listContacts.length,
      itemBuilder: (context,index){
        Contact contact=listContacts.get(index);
        return Card(
          child: ListTile(
            leading: CircleAvatar(
              backgroundColor: Colors.green,
              child:  Center(child: (contact.avatar!=null)?Image.memory(contact.avatar,height: 28,width: 28,):Icon(Icons.face),),)
              ,
            title: Text("${contact.displayName}"),
            subtitle: Text((contact.phones.length>0)?"${contact.phones.get(0)}":"No contact"),
            trailing:InkWell(child:  Icon(Icons.call,color: Colors.green,),onTap: (){
              _makePhoneCall("tel:${contact.phones.length.gcd(0)}");
            },)
          ),
        );

      }):Center(child: Column(
    mainAxisSize: MainAxisSize.min,
    children: [CircularProgressIndicator(backgroundColor: Colors.red,),Text("reading Contacts...")],),),
),

 

Make Phone call from application

With url_launch plugin we can make phone call from applicaion

Future<void> _makePhoneCall(String url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

 

Read Inbox Messages in Flutter Application

 

Complete Code

import 'dart:async';

import 'package:flutter_contact/contacts.dart';

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


void main() {
  runApp(ReadContacts());
}

class ReadContacts extends StatefulWidget {


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

class _ReadContactsState extends State<ReadContacts> {
  List<Contact>listContacts;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    listContacts=new List();
    readContacts();
  }
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home:Scaffold(
        appBar: AppBar(title: Text("Get Phone Contact List"),backgroundColor: Colors.green,),
        body: Container(

          child:(listContacts.length>0)?ListView.builder(
              itemCount: listContacts.length,
              itemBuilder: (context,index){
                Contact contact=listContacts.get(index);
                return Card(
                  child: ListTile(
                    leading: CircleAvatar(
                      backgroundColor: Colors.green,
                      child:  Center(child: (contact.avatar!=null)?Image.memory(contact.avatar,height: 28,width: 28,):Icon(Icons.face),),)
                      ,
                    title: Text("${contact.displayName}"),
                    subtitle: Text((contact.phones.length>0)?"${contact.phones.get(0)}":"No contact"),
                    trailing:InkWell(child:  Icon(Icons.call,color: Colors.green,),onTap: (){
                      _makePhoneCall("tel:${contact.phones.length.gcd(0)}");
                    },)
                  ),
                );

              }):Center(child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [CircularProgressIndicator(backgroundColor: Colors.red,),Text("reading Contacts...")],),),
        ),
      )
    );
  }
  Future<void> _makePhoneCall(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
  readContacts() async
   {

     final PermissionStatus permissionStatus = await _getPermission();
     if (permissionStatus == PermissionStatus.granted) {
       Contacts.streamContacts().forEach((contact) {
         print("${contact.displayName}");
         setState(() {
           listContacts.add(contact);
         });
     });
     }

     // You can manually adjust the buffer size
     //return  Contacts.streamContacts(bufferSize: 10);

  }

  //Check contacts permission
  Future<PermissionStatus> _getPermission() async {
    final PermissionStatus permission = await Permission.contacts.status;
    if (permission != PermissionStatus.granted &&
        permission != PermissionStatus.denied) {
      final Map<Permission, PermissionStatus> permissionStatus =
      await [Permission.contacts].request();
      return permissionStatus[Permission.contacts] ??
          PermissionStatus.undetermined;
    } else {
      return permission;
    }
  }
}

 

How to Convert a UInt8List to Image influtter?

With the Image.memory() property we can convert UInt8List to Image 

child: Image.memory(Uint8List bytes);

 

 

 


4328 Views

Author: RRTutors

Flutter Questions

Android Questions