0

I wrote this function to save contact number, but it can't save on local storage

Future _saveContact() async {
    Contact contact = Contact();
    contact.familyName = 'FreeZone';
    contact.phones = [Item(label: "mobile", value: '01752591591')];
    contact.emails = [Item(label: "work", value: 'info@34.71.214.132')];
    if (await Permission.contacts.request().isGranted) {
      await ContactsService.addContact(contact);
      print("Contact added successfully");
      return contact;
    }
  }

dependencies:

  • contacts_service: ^0.6.3
  • permission_handler: ^8.3.0

How to save contact according to the above-given Name, Number, Email?

James Z
  • 12,209
  • 10
  • 24
  • 44

3 Answers3

0

I could see 2 plugins in pub.dev that can do this for you in Android and iOS.

flutter_contact - A Flutter plugin to retrieve, create and save contacts and contact-related events on Android and iOS devices.

contacts_service - A Flutter plugin to retrieve and manage contacts on Android and iOS devices.

Please have a look into them.

Alok Dubey
  • 44
  • 5
0

Add this :

dependencies:
  contacts_service: ^0.6.3

then:

import 'package:contacts_service_example/contacts_list_page.dart';
import 'package:contacts_service_example/contacts_picker_page.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(ContactsExampleApp());

// iOS only: Localized labels language setting is equal to CFBundleDevelopmentRegion value (Info.plist) of the iOS project
// Set iOSLocalizedLabels=false if you always want english labels whatever is the CFBundleDevelopmentRegion value.
const iOSLocalizedLabels = false;

class ContactsExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
      routes: <String, WidgetBuilder>{
        '/add': (BuildContext context) => AddContactPage(),
        '/contactsList': (BuildContext context) => ContactListPage(),
        '/nativeContactPicker': (BuildContext context) => ContactPickerPage(),
      },
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    _askPermissions(null);
  }

  Future<void> _askPermissions(String routeName) async {
    PermissionStatus permissionStatus = await _getContactPermission();
    if (permissionStatus == PermissionStatus.granted) {
      if (routeName != null) {
        Navigator.of(context).pushNamed(routeName);
      }
    } else {
      _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) {
      final snackBar = SnackBar(content: Text('Access to contact data denied'));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    } else if (permissionStatus == PermissionStatus.permanentlyDenied) {
      final snackBar =
          SnackBar(content: Text('Contact data not available on device'));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Contacts Plugin Example')),
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            ElevatedButton(
              child: const Text('Contacts list'),
              onPressed: () => _askPermissions('/contactsList'),
            ),
            ElevatedButton(
              child: const Text('Native Contacts picker'),
              onPressed: () => _askPermissions('/nativeContactPicker'),
            ),
          ],
        ),
      ),
    );
  }
}
  • Hi Tasnuva. I have followed this code but it can't work here. So, I just wanted to know how to save contacts in mobile storage. I need a function where I set the default Number and Name, where users click on the button, it will ask for permission and after this save on Mobile Contact List. If you know how is possible kindly help me out. Thanks – Mian Zeeshan Jan 30 '22 at 16:44
0

I think I solved your problem.

_saveContact () async {
  // 'without Future' is working
  var newPerson = Contact();
  // newPerson uses Contact Package
  newPerson.givenName = 'FreeZone';
  newPerson.phones = [Item(label: "mobile", value: '01752591591')];
  newPerson.emails = [Item(label: "work", value: 'info@34.71.214.132')];

  if (await Permission.contacts.status.isGranted) {
    await ContactsService.addContact(newPerson);
    var contacts = await ContactsService.getContacts();
    print("Contact added successfully");


    return contacts;
  
    // setState(() {
    //   //setState isn't necessary, it just shows 'contact' directly on a screen.
    //   name = contacts;
    // //  I put 'contacts' in 'name' directly
    // });
  } 
}

Actually, I was in trouble using 'newPerson.phones'. I was wondering how to put my parameter in 'phone number'. However, with your code, I could know how to write the code.

And it is what I wrote you helped.

addPerson (given,family,number) async {
  var newPerson = Contact();

  newPerson.givenName = given;
  newPerson.familyName = family;
  newPerson.phones = [Item(label: "mobile", value: number)];
  // I wrote 'newPerson.phones = [number];' and it was wrong. 
  await ContactsService.addContact(newPerson);
  //  adding newPerson
  var contacts = await ContactsService.getContacts();
  //  call all of contacts
  setState(() {
    name = contacts;
  });
    //  to show the contacts directly, I use 'setState'.
  }
General Grievance
  • 4,555
  • 31
  • 31
  • 45