skip to Main Content

I’m using the json decoder on a List<List<int?>> json, and I’m having trouble converting the List<dynamic> to the List<List<int?>> I’d like to end up with. Is there a simple way to do this?

final jsonString = await rootBundle.loadString('lib/Permutations/$filename.json');
final jsonData = await json.decode(jsonString);
final data = List<List<int?>>.from(jsonData);

(TypeError (type ‘List<dynamic>’ is not a subtype of type
‘List<int?>’)

2

Answers


  1. seems that jsonData is List<dynamic>, while you are using that list of dynamic to build a two dimensional list of integers.

    so, you have two options either

    • casting that List<dynamic> to List<int?>

    final jsonData = await json.decode(jsonString) as List<int?>;

    Note : it’s not guaranteed to work.

    • build that list as it’s

    final data = List<List>.from(jsonData);

    Login or Signup to reply.
  2. The example below only works for the specified json format shown in jsonString., but the code can easily be modified for other formats.

    import 'dart:convert';
    
    void main() {
      // sample data, substitute for your code
      // final jsonString = await rootBundle.loadString('lib/Permutations/$filename.json');
      String jsonString = '[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]';
      
      // decode same as before (no need for await)
      final jsonData = json.decode(
        jsonString,
      );
    
      // map data
      final data = (jsonData as List).map(
        // function runs for each array in the outer array
        // return the correct data type in this case List<int>
        (e) {
          return List<int>.from(
            e,
          );
        },
    
        // convert to list from iterable
      ).toList();
    
      print(
        data.runtimeType,
      );
      print(
        data,
      );
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search