我想使用Flutter在移动的存储中保存联系人号码

nxagd54h  于 2023-05-29  发布在  Flutter
关注(0)|答案(3)|浏览(472)

我写这个函数是为了保存联系人号码,但是不能保存到本地存储

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;
    }
  }

依赖性:

  • 联系人_服务:^0.6.3
  • permission_handler:^8.3.0

如何根据上面给出的姓名、电话号码、电子邮件保存联系人?

kuhbmx9i

kuhbmx9i1#

我可以在www.example.com上看到2个插件pub.dev,它们可以在Android和iOS中为您做到这一点。
flutter_contact -一个Flutter插件,用于在Android和iOS设备上检索、创建和保存联系人和联系人相关事件。
contacts_service -一个Flutter插件,用于在Android和iOS设备上检索和管理联系人。
请调查一下。

ccrfmcuu

ccrfmcuu2#

添加这个:

dependencies:
  contacts_service: ^0.6.3

然后:

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'),
            ),
          ],
        ),
      ),
    );
  }
}
dnph8jn4

dnph8jn43#

我想我解决了你的问题。

_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
    // });
  } 
}

事实上,我在使用“newPerson. phones”时遇到了麻烦。我想知道如何把我的参数在'电话号码'。但是,有了你的代码,我就可以知道如何编写代码了。
你帮我写的东西。

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'.
  }

相关问题