【问题标题】:How to replace deprecated List [duplicate]如何替换已弃用的列表 [重复]
【发布时间】:2021-06-25 23:43:06
【问题描述】:

列表已被弃用。如何重写以下代码?

  RosterToView.fromJson(Map<String, dynamic> json) {
    if (json['value'] != null) {
      rvRows = new List<RVRows>();
      json['value'].forEach((v) {
        rvRows.add(new RVRows.fromJson(v));
      });
    }
  }

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    错误消息告诉您该怎么做。当我运行dart analyze 时,我得到:

       info • 'List' is deprecated and shouldn't be used. Use a list literal, [],
              or the List.filled constructor instead at ... • (deprecated_member_use)
              Try replacing the use of the deprecated member with the replacement.
      error • The default 'List' constructor isn't available when null safety is
              enabled at ... • (default_list_constructor)
              Try using a list literal, 'List.filled' or 'List.generate'.
    

    zero-argument List constructor 的文档还指出:

    此构造函数不能在 null 安全代码中使用。使用List.filled 创建一个非空列表。这需要一个填充值来初始化列表元素。要创建一个空列表,请使用[] 作为可增长列表,或使用List.empty 作为固定长度列表(或在运行时确定可增长性)。

    例子:

    var emptyList = [];
    
    var filledList = List<int>.filled(3, 0); // 3 elements all initialized to 0.
    filledList[0] = 0;
    filledList[1] = 1;
    filledList[2] = 2;
    
    var filledListWithNulls = List<int?>.filled(3, null);
    
    var generatedList = List<int>.generate(3, (index) => index);
    

    您也可以在这两种情况下使用 collection-for

    var filledList = [for (var i = 0; i < 3; i += 1) 0];
    var filledListWithNulls = <int?>[for (var i = 0; i < 3; i += 1) null];
    var generatedList = [for (var i = 0; i < 3; i += 1) i];
    

    【讨论】:

      【解决方案2】:

      根据官方文档:

      @Deprecated("使用列表字面量、[] 或 List.filled 构造函数")

      注意:此构造函数不能在 null 安全代码中使用。使用 List.filled 创建一个非空列表。这需要一个填充值来初始化列表元素。要创建一个空列表,请使用 [] 作为可增长列表,或使用 List.empty 作为固定长度列表(或在运行时确定可增长性)。

      您可以这样做:

      RosterToView.fromJson(Map<String, dynamic> json) {
          if (json['value'] != null) {
            rvRows = <RVRows>[];
            json['value'].forEach((v) {
              rvRows.add(new RVRows.fromJson(v));
            });
          }
        }
      

      另一种选择是:

      List<RVRows> rvRows = [];
      

      【讨论】:

        【解决方案3】:

        而不是: rvRows = new List();

        写: rvRows = [];

        【讨论】:

          猜你喜欢
          • 2015-06-25
          • 1970-01-01
          • 2013-05-08
          • 2013-11-23
          • 2013-10-15
          • 1970-01-01
          • 1970-01-01
          • 2020-02-27
          • 2012-10-02
          相关资源
          最近更新 更多