【问题标题】:Flutter Error: Expected a value of type 'FutureOr<List<dynamic>>', but got one of type '_JsonMap'颤振错误:预期类型为“FutureOr<List<dynamic>>”的值,但得到类型为“_JsonMap”的值之一
【发布时间】:2021-11-04 15:42:39
【问题描述】:

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

需要一个“FutureOr”类型的值,但得到一个“_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 响应。

标签: json flutter


【解决方案1】:

您从 JSON 中返回的值不是 List,而是 JSON 映射,因此您必须像这样更改 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);
  }

或者你可以按照here的回答来做。

【讨论】:

    猜你喜欢
    • 2023-01-02
    • 2022-10-14
    • 2021-05-29
    • 2021-10-30
    • 2021-07-13
    • 1970-01-01
    • 2021-11-03
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多