我已经对联系人进行了分组,但是当我在控制台中运行 print() 命令时,组列表为空。 为什么即使该联系人是群组成员,群组列表还是空的?
import 'package:flutter/material.dart';
import 'package:flutter_contacts/contact.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
class ContactsPage extends StatefulWidget {
const ContactsPage({super.key});
@override
State<ContactsPage> createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
List<Contact> _contacts =[];
@override
void initState() {
super.initState();
_fetchContacts();
}
Future _fetchContacts() async {
if (!await FlutterContacts.requestPermission()) {
} else {
List<Contact> contacts = await FlutterContacts.getContacts();
setState(() => _contacts = contacts);
print(_contacts);
}
return _contacts;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _fetchContacts(),
builder: (BuildContext context, index) {
return ListView.builder(
itemCount: _contacts.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(_contacts[index].groups[0].name),
);
}, );
},),
);
}
}
控制台结果:
I/flutter ( 9205): [Contact(id=253, displayName=A. H pahlozadeh, thumbnail=null, photo=null, isStarred=true, name=Name(first=, last=, middle=, prefix=, suffix=, nickname=, firstPhonetic=, lastPhonetic=, middlePhonetic=), phones=[], emails=[], addresses=[], organizations=[], websites=[], socialMedias=[], events=[], notes=[], accounts=[], groups=[])
通过您的日志,您可以注意到与您的联系人相关的所有属性都丢失了:
I/flutter ( 9205): [Contact(id=253, displayName=A. H pahlozadeh, thumbnail=null, photo=null, isStarred=true, name=Name(first=, last=, middle=, prefix=, suffix=, nickname=, firstPhonetic=, lastPhonetic=, middlePhonetic=), phones=[], emails=[], addresses=[], organizations=[], websites=[], socialMedias=[], events=[], notes=[], accounts=[], groups=[])
这是因为当您通过 FlutterContacts API 请求联系人时,您没有添加获取属性的参数。
为此,您可以这样做:
Future _fetchContacts() async {
if (!await FlutterContacts.requestPermission()) {
} else {
List<Contact> contacts = await FlutterContacts.getContacts(
withProperties: true); /// <---- HERE
setState(() => _contacts = contacts);
print(_contacts);
}
return _contacts;
}
您还可以在 pub.dev 中的包示例中看到这一点。