Save Contact to Phone

Sharing my code in case anyone looking for a way to save contact to phone

This will save the contact to the phone and open the contact in native Phone UI

PS: remember add Permission

  • Setting > Project Setup > Permissions > Contacts: Turn it on and enter a message.



Pub dependencesΒ 

  • flutter_contacts: ^1.1.6

import 'package:flutter_contacts/flutter_contacts.dart';

Future saveContact(
  String? firstName,
  String? middleName,
  String? lastName,
  String? prefix,
  String? email,
  String? mobile,
  String? title,
  String? company,
  String? work,
  String? url,
  String? fax,
  String? address,
  String? note,
) async {
  if (await FlutterContacts.requestPermission()) {
    final newContact = Contact();

    newContact.name.first = firstName ?? '';
    if (lastName?.isNotEmpty ?? false) {
      newContact.name.last = lastName ?? '';
    }
    if (middleName?.isNotEmpty ?? false) {
      newContact.name.middle = middleName ?? '';
    }
    if (prefix?.isNotEmpty ?? false) {
      newContact.name.prefix = prefix ?? '';
    }
    if (url?.isNotEmpty ?? false) {
      newContact.websites = [Website(url ?? '')];
    }
    if (email?.isNotEmpty ?? false) {
      newContact.emails = [Email(email ?? '')];
    }
    if (note?.isNotEmpty ?? false) {
      newContact.notes = [Note(note ?? '')];
    }
    if (address?.isNotEmpty ?? false) {
      newContact.addresses = [Address(address ?? '')];
    }
    newContact.organizations = [
      Organization(company: company ?? '', title: title ?? '')
    ];
    List<Phone> _phones = [];
    if (mobile?.isNotEmpty ?? false) {
      _phones.addAll([Phone(mobile ?? '')]);
    }
    if (work?.isNotEmpty ?? false) {
      _phones.addAll([Phone(work ?? '', label: PhoneLabel.work)]);
    }
    if (fax?.isNotEmpty ?? false) {
      _phones.addAll([Phone(fax ?? '', label: PhoneLabel.faxWork)]);
    }
    if (_phones.isNotEmpty) {
      newContact.phones = _phones;
    }


    final saved_contact = await newContact.insert();
    await FlutterContacts.openExternalEdit(saved_contact.id);
  }
}
3
1 reply