0

If I am not sure a list is null or not, I could do

final something = myList?[0].property;

What if I knew myList existed but was not sure there is an element in it?

Do I need to manually check that isNotEmpty?

final something = myList[0]?.property;

says The receiver can't be null, so the null-aware operator '?.' is unnecessary.

user3808307
  • 2,270
  • 9
  • 45
  • 99

2 Answers2

1

You need to define your list to be nullable.

e.g.:

List<myObject?> myList = [myObject(), null, null, myObject()]

// then error is not shown

final something = myList[0]?.property;

Example

void main() {
 List<int?> list = null; 
   
  for (var i = 0; i< list.length; i++ ) {
    print(list[i]?.isEven);   
  }
  
 // Error: The value 'null' can't be assigned to a variable of type 'List<int?>' because 
 // 'List<int?>' is not nullable.
 // - 'List' is from 'dart:core'.
 // List<int?> list = null; 
  
  
  List<int?> list2 = [null, 2, 1, 3, null]; 
   
  for (var i = 0; i< list2.length; i++ ) {
    print(list2[i]?.isEven);   
  }
  
 // no error

List<int?> list3 = []; 
print(list3[5]?.isEven); 

//no error


  
}
orotype
  • 449
  • 4
  • 8
0

Yes. you need to check it is empty or not.

if myList exist and not null

late List<dynamic> myList;

myList = [];
if (myList.length > 0){

}

if myList can be null

late List<dynamic>? myList;

if (myList != null && myList!.length > 0) {

}
MobIT
  • 880
  • 6
  • 15