CastList<dynamic,String> is not an subtype of type String even after placing cast() flutter dart

Viewed 104

Trying to parse json response, works fine with string, int type values. But getting error when having list as values even after placing cast(). Error image is placed at bottom

class ChennaiModel{
  final int ra;
  final String ci;
  final bool lo;
  final List<String> ab;

  ChennaiModel({
    this.ra,this.ci,this.lo,this.ab
  });


  factory ChennaiModel.fromJson(Map<String,dynamic>parsedjson){
var streetsFromJson  = parsedjson['streets'];
 List<String> streetsList = streetsFromJson.cast<String>();
    return new ChennaiModel(
         ra:parsedjson['rank'],
         ci:parsedjson['city'],
         lo:parsedjson['love'],
         ab:streetsList

    );
  }
}

Future<ChennaiModel> getchennai() async {
  final response = await http.get(Uri.https('run.mocky.io','/v3/1496b5ef-873a-48db-9550-75195f2db3b4'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return ChennaiModel.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

enter image description here

1 Answers

The error isn't in json parsing. The actual error is while building the ui, then using the Text() widget which expects an input as String.If we pass the entire list we get this error. So we need to Iterate and display in Ui. Solved by using ListView.builder() to iterate the list.

ListView.builder(
               
                itemCount: snapshot.data.ab.length,
                itemBuilder: (context,index){
                return Text(snapshot.data.ab[index]);
              }),
Related