Я начал изучать Дарт, но застрял.
Я следую этому учебнику , но что-то идет не так.
Вот проблема: Я бы хотел обратиться к API и извлечь из него данные. Приятно!
Я импортировал пакеты для выполнения запросов и конвертации. API возвращает данные правильно. HTTP GET работает.
Проблемы возникли, когда я пытался назначить json.decode(response.body)
на Map()
.
Всегда говорится: The argument type dynamic cannot be assigned to the parameter type Map<String, dynamic>
.
Может кто-нибудь объяснитьпочему это происходит и как с этим справиться? Я использую Android Studio. Я вызываю функцию в StatefulWidget:
var trends = fetchData('getAll', params);
, где params
- это карта ().
Код:
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,
....
}
]
}