'Flutter The argument type 'String' can't be assigned to the parameter type 'Map<String, dynamic>'
I got the problem when I want to fetch Data from PONS API.
import 'package:eng_it_translator/model/model.dart';
import 'package:http/http.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
class Network {
Future<Vocabulary> fetchData({String keyword}) async {
var headers = {
'X-Secret':
'XXXXXXXXXXXXX',
};
var params = {
'q': 'house',
'l': 'deen',
};
var query = params.entries.map((p) => '${p.key}=${p.value}').join('&');
var url = Uri.parse("https://api.pons.com/v1/dictionary?$query");
var res = await http.get(url, headers: headers);
if (res.statusCode == 200) {
var data = json.decode(res.body);
var realdata =
List<Vocabulary>.from(data).map((x) => Vocabulary.fromJson(x));
print(realdata);
} else {
throw Exception('http.get error: statusCode= ${res.statusCode}');
}
}
}
The argument type 'Vocabulary' can't be assigned to the parameter type 'Map<String, dynamic>'.
Body of DATA is in Map structure, but I can't transform it to List.
class Vocabulary {
String lang;
List<Hits> hits;
Vocabulary({this.lang, this.hits});
Vocabulary.fromJson(Map<String, dynamic> json) {
lang = json['lang'];
if (json['hits'] != null) {
hits = new List<Hits>();
json['hits'].forEach((v) {
hits.add(new Hits.fromJson(v));
});
}
}
Solution 1:[1]
I think you must convert json to Map try this
hits: json['hits'] != null
? json['hits'].map<Hits>((v) => new Hits.fromJson(v)).toList()
Solution 2:[2]
You can convert your Vocabulary data to List by adding toList()
List.from(data)
.map((x) => Vocabulary.fromJson(x))
.toList());
Solution 3:[3]
There is a reason for the error. If you print res.body
you will find that it is a JSON object. JSON and JSON object is different in a way that in JSON there needs to be "" around key also. for e.g.
name:"Pramod" // valid JSON object. Invalid JSON
"name":"Pramod" // valid JSON. valid json object.
To solve your problem, first convert res.body
to valid JSON.
String s = json.encode(res.body);
Then covert it to JSON object you would like
Student student = Student.fromJson(jsonDecode(s)); // there is no typo here
Note: jsonDecode comes from dart:convert
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tawfik al |
Solution 2 | Kashifa |
Solution 3 | Pramod |