【问题标题】:HTTP Get Json and Cast To Dart MapHTTP 获取 Json 并转换为 Dart 映射
【发布时间】:2020-02-14 12:03:16
【问题描述】:

我已经开始学习 Dart,但我卡住了。

我关注了this tutorial,但出了点问题。

问题出在这里:我想联系一个 API 并从中获取数据。好的!

我已经导入了用于请求和转换的包。 API 正确返回数据。 HTTP GET 正在运行。

当我尝试将json.decode(response.body) 分配给Map() 时,麻烦就来了。

它总是说:The argument type dynamic cannot be assigned to the parameter type Map<String, dynamic>

有人能解释一下为什么会发生这种情况以及如何处理吗? 我正在使用安卓工作室。我在 StatefulWidget 中调用函数:

var trends = fetchData('getAll', params);

params 是一个 Map()。

代码:

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

Future<ApiResponse> fetchData(String command, Map params) async {
  final String url =
      'https://example.com/api/v2/....';

  final response = await http.get(url);

  if (response.statusCode == 200) {

    return ApiResponse.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

}

class ApiResponse{
  final String result;
  final String error;
  final String error_number;
  final String response_code;

  PopnableResponse(
      {this.result, this.error, this.error_number, this.response_code});

  factory ApiResponse.fromJson(Map<String, dynamic> json) {

    return ApiResponse(
      result: json['result'] as String,
      error: json['error'] as String,
      error_number: json['error_number'] as String,
      response_code: json['response_code'] as String,
    );
  }
}

JSON 示例:

{
   "error":"",
   "error_number":"",
   "response_code":200,
   "result":[
      {
         "id":1,
         "name":"Great Deal",
         "day_aired":"2015-07-05 11:06:09",
         "trend":"Noone"
      },
      {
         "id":2,
         ....
      }
   ]
}

【问题讨论】:

  • Nitpick:你写了json['result'] as String,但示例 JSON 的 result 值不是字符串。

标签: android-studio flutter dart


【解决方案1】:

尝试投射它

json.decode(response.body) as Map<String, dynamic>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2020-07-14
    • 1970-01-01
    • 2021-03-21
    • 2014-12-24
    • 2017-06-01
    • 1970-01-01
    相关资源
    最近更新 更多