_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>') flutter

北城余情 提交于 2020-01-06 05:42:32

问题


I have a problem since 2 hours. I have this error, i saw more topics but i can't solve it.

The message : _TypeError (type 'List' is not a subtype of type 'Map') flutter

My Model :


class Theme {

  int id;
  String name;

  Theme({this.id, this.name});

  factory Theme.fromJson(Map<String, dynamic> json) {
    return Theme(
      id: json['id'],
      name: json['name'],
    );
  }

  Future<Theme> getThemes() async {
    String url = 'http://10.0.2.2:3000/v1/api/theme';
    final response =
        await http.get(url, headers: {"Accept": "application/json"});


    if (response.statusCode == 200) {
      return Theme.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load themes');
    }
  }

}

My Theme Screen:


class _Theme extends State<Theme> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Blackbox"),
        ),
        body: Center(
          child: FutureBuilder<t.Theme>(
            future: t.Theme().getThemes(), //sets the getQuote method as the expected Future
            builder: (context, snapshot) {
              if (snapshot.hasData) { 
                new ListView.builder(
                  itemCount: _lengthList,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      child: new Text('${snapshot.data.name}'),
                    );
                  },
                );//checks if the response returns valid data              
              } else if (snapshot.hasError) { //checks if the response throws an error
                return Text("${snapshot.error}");
              }
              return CircularProgressIndicator();
            },
          ),
        ),
    );
  }
}

I tried more tutorials and differents topics but i have the same error...

Thank you !


回答1:


jsonDecode(String source) return a List if the json is like this:

[{"id": 1,"name":"test theme"}]

and returns a Map<String,dynamic> if the json looks like this:

{"id": 1,"name":"test theme"}

if you want to use the first theme you should do this:

 if (response.statusCode == 200) {
      return Theme.fromJson(json.decode(response.body)[0]); // this will return the first theme map
    } else {
      throw Exception('Failed to load themes');
    }

and if you want to convert all the themes in the json to Theme objects you need to go over the list and convert them one by one:

Future<List<Theme>> getThemes() async {
  String url = 'http://10.0.2.2:3000/v1/api/theme';
  final response = await get(url, headers: {"Accept": "application/json"});

  if (response.statusCode == 200) {
    List themesList = jsonDecode(response.body);
    List<Theme> themes = [];
    for(var themeMap in themesList){
      themes.add(Theme.fromJson(themeMap));
    }
    return themes;
  } else {
    throw Exception('Failed to load themes');
  }
}


来源:https://stackoverflow.com/questions/57977863/typeerror-type-listdynamic-is-not-a-subtype-of-type-mapstring-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!