【问题标题】:Flutter nullsafety: conditional List positionFlutter nullsafety:条件列表位置
【发布时间】:2021-05-06 10:46:16
【问题描述】:

如果我不确定列表是否为空,我可以这样做

final something = myList?[0].property;

如果我知道myList 存在但不确定其中是否存在元素怎么办?

我需要手动检查 isNotEmpty 吗?

final something = myList[0]?.property;

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

【问题讨论】:

    标签: flutter dart-null-safety


    【解决方案1】:

    您需要将列表定义为可为空。

    例如:

    List<myObject?> myList = [myObject(), null, null, myObject()]
    
    // then error is not shown
    
    final something = myList[0]?.property;
    
    

    示例

    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
    
    
      
    }
    

    【讨论】:

    • 我认为这行不通。列表可以为 null 并且为空,myList[0] 会抛出错误
    • 我的意思不是空的和空的
    • 我需要的是一个不可为空的列表,我可以检查索引
    【解决方案2】:

    是的。你需要检查它是否为空。

    如果 myList 存在且不为空

    late List<dynamic> myList;
    
    myList = [];
    if (myList.length > 0){
    
    }
    

    如果 myList 可以为空

    late List<dynamic>? myList;
    
    if (myList != null && myList!.length > 0) {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-03
      • 2022-09-23
      • 2021-06-05
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 2018-08-23
      • 2018-09-09
      • 2018-08-08
      相关资源
      最近更新 更多