0

List has been deprecated. How do I re-write the following code?

  RosterToView.fromJson(Map<String, dynamic> json) {
    if (json['value'] != null) {
      rvRows = new List<RVRows>();
      json['value'].forEach((v) {
        rvRows.add(new RVRows.fromJson(v));
      });
    }
  }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Paul Coshott
  • 735
  • 1
  • 9
  • 16

3 Answers3

2

According to the official documentation:

@Deprecated("Use a list literal, [], or the List.filled constructor instead")

NOTICE: This constructor cannot be used in null-safe code. Use List.filled to create a non-empty list. This requires a fill value to initialize the list elements with. To create an empty list, use [] for a growable list or List.empty for a fixed length list (or where growability is determined at run-time).

You can do this instead:

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

Another option is:

List<RVRows> rvRows = [];
Bach
  • 2,928
  • 1
  • 6
  • 16
0

Instead of: rvRows = new List();

Write: rvRows = [];

0

The error message tells you what to do. When I run dart analyze, I get:

   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'.

The documentation for the zero-argument List constructor also states:

This constructor cannot be used in null-safe code. Use List.filled to create a non-empty list. This requires a fill value to initialize the list elements with. To create an empty list, use [] for a growable list or List.empty for a fixed length list (or where growability is determined at run-time).

Examples:

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);

You also could use collection-for for both cases:

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];
jamesdlin
  • 81,374
  • 13
  • 159
  • 204