简体   繁体   中英

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

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 ? will allow you to access the element at 0, which is causing the error.

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 ?? '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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