【发布时间】:2021-02-25 20:27:01
【问题描述】:
我正在学习在flutter app中使用Contacts,在理解和编写代码的过程中,我看到了这个表达-_contacts?.length ?? 0,
我不明白这是什么意思,这里问号有什么用?
这是完整的代码 -
import 'package:flutter/material.dart';
import 'package:contacts_service/contacts_service.dart';
class ContactsPage extends StatefulWidget {
@override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
Iterable<Contact> _contacts;
@override
void initState() {
getContacts();
super.initState();
}
Future<void> getContacts() async {
//Make sure we already have permissions for contacts when we get to this
//page, so we can just retrieve it
final Iterable<Contact> contacts = await ContactsService.getContacts();
setState(() {
_contacts = contacts;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: (Text('Contacts')),
),
body: _contacts != null
//Build a list view of all contacts, displaying their avatar and
// display name
? ListView.builder(
itemCount: _contacts?.length ?? 0,
itemBuilder: (BuildContext context, int index) {
Contact contact = _contacts?.elementAt(index);
return ListTile(
contentPadding:
const EdgeInsets.symmetric(vertical: 2, horizontal: 18),
leading: (contact.avatar != null && contact.avatar.isNotEmpty)
? CircleAvatar(
backgroundImage: MemoryImage(contact.avatar),
)
: CircleAvatar(
child: Text(contact.initials()),
backgroundColor: Theme.of(context).accentColor,
),
title: Text(contact.displayName ?? ''),
//This can be further expanded to showing contacts detail
// onPressed().
);
},
)
: Center(child: const CircularProgressIndicator()),
);
}
}
这是页面的链接 - How to access contacts in flutter
【问题讨论】: