How To Access Phone Contacts in Flutter?

How To Access Phone Contacts in Flutter

Accessing phone contacts saved on a mobile phone is one of the most common things that as mobile app developers, we will come across.

While there are quite a few ways of accessing phone contacts in Flutter, I prefer the simplest way to fetch phone contact details in Flutter, which I explain below. But in short, working with phone contacts in Flutter, that’s a good thing to know before we begin 🙂

We will use a Flutter contact picker and the end result will look like this:

How To Access Phone Contacts using Flutter

Access Phone Contacts Using Flutter

In order to access phone contacts using Flutter, the first thing we will need to do is add the flutter_native_contact_picker package to our Flutter project. We will do this by adding the package to the pubspec.yaml file of our project.

At the time of writing this, the latest version of the package is flutter_native_contact_picker: ^0.0.4. You can download the package from here.

Fetch phone contacts using Flutter

You don’t need to manually do flutter pub get anymore but in case you need to, save the pubspec.yaml file after adding the package (take special care of spacing while adding the package to the yaml file) and then run the following command in the terminal.

flutter pub get

The UI we create to show an example of how to access phone book using Flutter, is quite simple. We only have 3 elements:

  • Label to tell the user to Click below to pull up the phone’s contacts (Optional)
  • An ElevatedButton to show the phone’s contact when clicked
  • A label to show the selected phone number (Optional)

Now, let’s head to the main.dart file of the project and delete everything there. Then, paste the following code and save the file.

import 'package:flutter/material.dart';
import 'package:flutter_native_contact_picker/flutter_native_contact_picker.dart';

void main() {
  runApp(const FlutterContacts());
}

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

  @override
  State<FlutterContacts> createState() => _FlutterContactsState();
}

class _FlutterContactsState extends State<FlutterContacts> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Contacts',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.brown),
      home: const MainPage(),
    );
  }
}

final FlutterContactPicker _contactPicker = FlutterContactPicker();
Contact? _contact;
String? selectedNumber;

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Contacts'),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const SizedBox(
                  height: 20.0,
                ),
                Text(
                  'Click below to show contacts..',
                  textAlign: TextAlign.center,
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
                const SizedBox(
                  height: 20.0,
                ),
                ElevatedButton(
                  onPressed: () async {
                    Contact? contact = await _contactPicker.selectContact();

                    if (contact != null) {
                      setState(() {
                        _contact = contact;
                        List<String>? phoneNumbers = contact!.phoneNumbers;
                        selectedNumber = phoneNumbers?[0] ?? 'Nothing selected';
                      });
                    }
                  },
                  child: const Text('Show Contacts'),
                ),
                const SizedBox(
                  height: 30.0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text(
                      'Number: ',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(selectedNumber ?? 'No Number selected'),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

We are not doing anything fancy here. The only thing to note here are the following object and the variable that we will be using to fetch the contacts on the phone.

The FlutterContactPicker comes from the package we added to our project to access the phone contacts on the device. We use the final _contactPicker below, to get and store the selected contact, as below:

.....
...
ElevatedButton(
   onPressed: () async {
      Contact? contact = await _contactPicker.selectContact();
          if (contact != null) {
                setState(() {
                    _contact = contact;
                     List<String>? phoneNumbers = contact!.phoneNumbers;
                        selectedNumber = phoneNumbers?[0] ?? 'Nothing selected';
                     });
               }
           },
  child: const Text('Show Contacts'),
),
.....
...

Here, on click of our ElevatedButton,the line Contact? contact = await _contactPicker.selectContact(); already gives us the selected contact or null, in case the user clicked Cancel.

Then, in the following line, we display the selected contact in a Label.

Please also note that contact!.phoneNumbers returns all the phone numbers (work, home, mobile…) a contact can have. For this example, we only consider the first one, hence phoneNumbers?[0].

If you want to download this project and dig into the code, you can do so by pulling it down from GitHub, here.

Share This Post

1 thought on “How To Access Phone Contacts in Flutter?”

  1. Pingback: How I Created a Flutter App Without Writing ANY Code, using ChatGPT? - Rajiv Verma

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe To my Future Posts

Get notified whenever I post something new

More To Explore