Home > Software engineering >  How to convert List<List<dynamic>> to List<List<String>> without using itera
How to convert List<List<dynamic>> to List<List<String>> without using itera

Time:09-02

I have a 2d dynamic list which is being read from a json file and want to convert it into a 2d string list.

CurrentPuzzle({
    List<List<String>> letterMat = const [],
  })  : _letterMat = letterMat;

factory CurrentPuzzle.fromJSON(dynamic jsonData) {
    return CurrentPuzzle(
      letterMat: List<List<String>>.from(jsonData['current_puzzle']['_letterMat']),
    );

Data is being read from a json file

{
  "current_puzzle": {
    "_letterMat": [
      ["z", "b", "a"],
      ["c", "d", "e"],
      ["f", "g", "h"],
      ["i", "j", "k"]
    ]
  }
}

I have tried using

List<List<String>>.from(jsonData['current_puzzle']['_letterMat'])

but run into an error of:

Exception has occurred.
_TypeError (type 'List<dynamic>' is not a subtype of type 'List<String>')

Anysort of help is appreciated!

CodePudding user response:

Without the rest of your code this is just a guess. But try:

final newList = 2d_dyn_list.map((o) => o.map((i) => i.toString()).toList()).toList();

CodePudding user response:

I tried it under the premise that I mapped json data.

final map = {
    "current_puzzle": {
      "_letterMat": [
        ["z", "b", "a"],
        ["c", "d", "e"],
        ["f", "g", "h"],
        ["i", "j", "k"]
      ]
    }
  };

List<List<String>> letterMat = const [];
    letterMat = List<List<String>>.from(map['current_puzzle']!['_letterMat']!);
    print(letterMat); //[[z, b, a], [c, d, e], [f, g, h], [i, j, k]]

CodePudding user response:

You don't need from, try this:

factory CurrentPuzzle.fromJSON(dynamic jsonData) {
    return CurrentPuzzle(
      letterMat: jsonData['current_puzzle']['_letterMat'] as List<List<String>>,
    ); // [["z", "b", "a"],["c", "d", "e"],["f", "g", "h"],["i", "j", "k"]]

CodePudding user response:

I have tried using

List<List<String>>.from(jsonData['current_puzzle']['_letterMat'])

That would work only if the sublists each has a runtimeType of List<String>. As stated by the List<E>.from documentation:

All the elements should be instances of E.

The elements are of type List<dynamic>, which is not a subtype of List<String>. (Related: Difference between List<String>.from() and as List<String> in Dart)

You instead need to create a new List and to use List.from (or alternatively List.cast) on each sublist. For example:

var listOfDynamicLists = [
  <dynamic>['foo', 'bar'],
  <dynamic>['baz', 'qux'],
];

var newList = [
  for (var sublist in listOfDynamicLists) sublist.cast<String>(),
];
  • Related