[英]What does this line “_contacts?.length ?? 0” means in flutter/dart
我正在學習在 flutter 應用程序中使用聯系人,在理解和編寫代碼時,我看到了這個表達式 - _contacts?.length?? 0,
_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()),
);
}
}
這是頁面的鏈接 - 如何訪問 flutter 中的聯系人
它首先檢查_contacts
。 如果不是 null,它會檢查_contacts.length
。 如果_contacts.length
不是 null,則設置其值,否則設置為零。
_contacts?.length?? 0
第一?
表示如果聯系人是null
,請不要嘗試調用 length 並只返回null
因為在 null 上調用.length
會引發錯誤。 所以基本上你避免了null
指針錯誤。
第二個??
表示如果contacts
或length
為null
(即??
之前的值),則返回0
。
Dart 語言導覽 - 運算符部分是 Dart 運算符的一個很好的參考。
這意味着如果_contacts
數組是null
,您將得到0
的length
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.