简体   繁体   English

Dart 对变量使用 Null 安全

[英]Dart using Null safe for variables

in this below code _invoiceInformation in first initialize is null and i'm trying to use dart null safe to manage that in my flutter applications在下面的代码中,第一次初始化中的_invoiceInformationnull ,我正在尝试使用dart null safe 在我的flutter应用程序中管理它

in this code although i used ?在这段代码中,虽然我使用了? operation i still get error:操作我仍然得到错误:

Error:错误:

RangeError (index): Index out of range: no indices are valid: 0 

what i want to try:我想尝试什么:

_invoiceInformation = Hive.box<InvoiceInformation>('invoice_information');
_province.text=_invoiceInformation?.getAt(0)?.province??'';
_province.text=_invoiceInformation?.getAt(0)?.province??'';

If the list _invoiceInformation is empty ie having zero elements, then the null aware operator ?如果列表_invoiceInformation为空,即具有零个元素,那么空感知运算符? will allow you to access the element at 0, which is causing the error.将允许您访问 0 处的元素,这会导致错误。

You will also have to check whether the list is empty or not before accessing its elements.在访问其元素之前,您还必须检查列表是否为空。

if(_invoiceInformation != null && _invoiceInformation.isNotEmpty) {
    _province.text=_invoiceInformation.getAt(0)?.province ?? '';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM