Flutter错误:期望值的类型为“FutureOr<List<dynamic>>”,但得到的却是“_JsonMap”类型。

4

当我尝试解码JSON时,出现以下错误:

期望值的类型为'FutureOr<List>',但得到了'_JsonMap'类型

这是我从API获取数据的代码:

Future<List> getData() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'token';
    final value = prefs.get(key) ?? 0;

    String myUrl = "$serverUrl/userchecks";
    http.Response response = await http.get(Uri.parse(myUrl), headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer $value'
    });

    print('Response status : ${response.statusCode}');

    return json.decode(response.body);
  }

分享你的JSON响应。 - Benyamin
1个回答

3

你从JSON中返回的值不是一个List,而是一个JSON map,因此你需要像这样更改Future返回类型:

Future<Map<String,dynamic>> getData() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'token';
    final value = prefs.get(key) ?? 0;

    String myUrl = "$serverUrl/userchecks";
    http.Response response = await http.get(Uri.parse(myUrl), headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer $value'
    });

    print('Response status : ${response.statusCode}');

    return json.decode(response.body);
  }

或者您可以按照这里的回答进行操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接