Flutter联系人管理插件contacts_plugin_plus的使用
Flutter联系人管理插件contacts_plugin_plus的使用
在本教程中,我们将介绍如何使用 contacts_plugin_plus
插件来管理和操作设备上的联系人。该插件支持 Android 和 iOS 平台。
支持Android和iOS端
选择联系人
通过 selectContact()
方法可以选择一个联系人:
ContactsPlugin.selectContact().then((value) {
var name = value.name ?? "";
var number = value.number ?? "";
setState(() {
selectText = name + "/" + number;
});
});
获取全部联系人
通过 getAllContacts()
方法可以获取所有联系人:
ContactsPlugin.getAllContacts().then((value) {
for (var contact in value) {
var number = "";
if (contact.phones != null && contact.phones!.isNotEmpty) {
number = contact.phones?.first.value ?? "";
}
var name = contact.otherName ?? "";
debugPrint("phone:" + number);
debugPrint("name:" + name);
}
setState(() {
allContacts = "The number of all contacts is:" + value.length.toString();
});
});
示例代码
以下是完整的示例代码,展示了如何在 Flutter 应用程序中使用 contacts_plugin_plus
插件。
import 'dart:async';
import 'package:contacts_plugin_plus/contacts_plugin.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'button.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
[@override](/user/override)
void initState() {
super.initState();
initPlatformState();
}
// 初始化平台状态
Future<void> initPlatformState() async {
String platformVersion;
try {
platformVersion = await ContactsPlugin.platformVersion ?? 'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
var selectText = "SelectContact";
var allContacts = "getAllContacts";
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: [
Container(
margin: const EdgeInsets.only(top: 20),
child: Text('Running on: $_platformVersion\n'),
),
Button(
text: selectText,
margin: const EdgeInsets.fromLTRB(34.0, 35.0, 34.0, 0.0),
click: () async {
if (await Permission.contacts.request().isGranted) {
ContactsPlugin.selectContact().then((value) {
var name = value.name ?? "";
var number = value.number ?? "";
setState(() {
selectText = name + "/" + number;
});
});
debugPrint("Permission granted");
} else {
// 权限被拒绝,请自行处理
debugPrint("Permission denied");
}
},
),
Button(
text: allContacts,
margin: const EdgeInsets.fromLTRB(34.0, 35.0, 34.0, 0.0),
click: () async {
if (await Permission.contacts.request().isGranted) {
ContactsPlugin.getAllContacts().then((value) {
for (var contact in value) {
var number = "";
if (contact.phones != null && contact.phones!.isNotEmpty) {
number = contact.phones?.first.value ?? "";
}
var name = contact.otherName ?? "";
debugPrint("phone:" + number);
debugPrint("name:" + name);
}
setState(() {
allContacts = "The number of all contacts is:" + value.length.toString();
});
});
debugPrint("Permission granted");
} else {
// 权限被拒绝,请自行处理
debugPrint("Permission denied");
}
},
)
],
),
),
);
}
}
更多关于Flutter联系人管理插件contacts_plugin_plus的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter联系人管理插件contacts_plugin_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,关于如何在Flutter应用中使用contacts_plugin_plus
插件来管理联系人,以下是一个详细的代码案例,涵盖了基本的联系人读取和写入操作。
环境设置
首先,确保你的Flutter项目中已经添加了contacts_plugin_plus
依赖。在pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter:
sdk: flutter
contacts_plugin_plus: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
Android权限配置
在android/app/src/main/AndroidManifest.xml
中添加必要的权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<!-- 其他配置 -->
</manifest>
iOS权限配置
在ios/Runner/Info.plist
中添加必要的权限描述:
<key>NSContactsUsageDescription</key>
<string>This app needs access to your contacts to manage them.</string>
请求权限
在你的Dart代码中,使用permission_handler
插件来请求权限(如果尚未添加,请先在pubspec.yaml
中添加依赖):
dependencies:
permission_handler: ^x.y.z # 请替换为最新版本号
然后,在代码中请求权限:
import 'package:permission_handler/permission_handler.dart';
import 'package:contacts_plugin_plus/contacts_plugin_plus.dart';
Future<void> requestPermissions() async {
var status = await Permission.contacts.status;
if (!status.isGranted) {
Map<Permission, PermissionStatus> permissions = await Permission.contacts.request();
status = permissions[Permission.contacts] ?? status;
}
if (!status.isGranted) {
throw Exception('Contacts permission is required.');
}
}
读取联系人
以下代码展示了如何读取联系人:
Future<List<Contact>> getContacts() async {
await requestPermissions();
ContactsPlugin contactsPlugin = ContactsPlugin();
Iterable<Contact> contacts = await contactsPlugin.getContacts(withThumbnails: false);
return contacts.toList();
}
添加联系人
以下代码展示了如何添加新联系人:
Future<void> addContact() async {
await requestPermissions();
ContactsPlugin contactsPlugin = ContactsPlugin();
Contact newContact = Contact(
givenName: 'John',
familyName: 'Doe',
phones: [Item(label: 'mobile', value: '1234567890')],
emails: [Item(label: 'work', value: 'john.doe@example.com')],
);
await contactsPlugin.addContact(newContact);
}
更新联系人
以下代码展示了如何更新现有联系人(假设你已经知道要更新的联系人的ID):
Future<void> updateContact(String contactId) async {
await requestPermissions();
ContactsPlugin contactsPlugin = ContactsPlugin();
Contact updatedContact = Contact(
id: contactId,
givenName: 'Johnny', // 更新名字
familyName: 'Doe',
phones: [Item(label: 'mobile', value: '0987654321')], // 更新电话号码
emails: [Item(label: 'work', value: 'johnny.doe@example.com')], // 更新电子邮件
);
await contactsPlugin.updateContact(updatedContact);
}
删除联系人
以下代码展示了如何删除现有联系人(假设你已经知道要删除的联系人的ID):
Future<void> deleteContact(String contactId) async {
await requestPermissions();
ContactsPlugin contactsPlugin = ContactsPlugin();
await contactsPlugin.deleteContact(contactId);
}
完整示例
以下是一个完整的示例,展示了如何在一个Flutter应用中集成并使用contacts_plugin_plus
:
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:contacts_plugin_plus/contacts_plugin_plus.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Contacts Plugin Example'),
),
body: ContactManager(),
),
);
}
}
class ContactManager extends StatefulWidget {
@override
_ContactManagerState createState() => _ContactManagerState();
}
class _ContactManagerState extends State<ContactManager> {
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () async {
try {
List<Contact> contacts = await getContacts();
// 处理联系人列表
} catch (e) {
// 处理错误
}
},
child: Text('Get Contacts'),
),
ElevatedButton(
onPressed: () async {
try {
await addContact();
} catch (e) {
// 处理错误
}
},
child: Text('Add Contact'),
),
// 可以添加更多按钮来演示更新和删除操作
],
),
);
}
Future<List<Contact>> getContacts() async {
var status = await Permission.contacts.status;
if (!status.isGranted) {
Map<Permission, PermissionStatus> permissions = await Permission.contacts.request();
status = permissions[Permission.contacts] ?? status;
}
if (!status.isGranted) {
throw Exception('Contacts permission is required.');
}
ContactsPlugin contactsPlugin = ContactsPlugin();
Iterable<Contact> contacts = await contactsPlugin.getContacts(withThumbnails: false);
return contacts.toList();
}
Future<void> addContact() async {
var status = await Permission.contacts.status;
if (!status.isGranted) {
Map<Permission, PermissionStatus> permissions = await Permission.contacts.request();
status = permissions[Permission.contacts] ?? status;
}
if (!status.isGranted) {
throw Exception('Contacts permission is required.');
}
ContactsPlugin contactsPlugin = ContactsPlugin();
Contact newContact = Contact(
givenName: 'John',
familyName: 'Doe',
phones: [Item(label: 'mobile', value: '1234567890')],
emails: [Item(label: 'work', value: 'john.doe@example.com')],
);
await contactsPlugin.addContact(newContact);
}
}
请根据你的具体需求进一步扩展和完善这个示例。注意,在实际应用中,应该添加更多的错误处理和用户反馈机制。