Search code examples
dartdart-null-safety

How to add item to list with Null Safety


I have problem working with null safety in dart.

void main() {
  List<String>? testlist;
  testlist?.add('null test');
  print(testlist);
}

Why the printed testlist is still null?


Solution

  • Your testlist is still null, because you defined it as nullable and did not initialize it.

    So when it comes to adding an entry to your testlist, while calling testlist?.add('null test');. A check will be performed, if testlist is null. If it is null, the call for add will be skipped. And in your case, it is always null.

    So to visualize the null-conditional operator in your code line testlist?.add('null test');. It could also be written as:

    List<String>? testlist;
    
    // testlist?.add('null test');  
    if(testlist != null) {
        testlist.add('null test');
    }
      
    print(testlist);
    

    If you want to add the string, you have to initialize your testlist:

    List<String>? testlist = [];
    

    Or if possible you could avoid the nullable and write your code as:

    List<String> testlist = [];
    testlist.add('null test');
    print(testlist);