Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
void makeLoginReq() async {
String url = 'https://travel.prabidhee.com/api/login';
Map map = {
'email': email,
'password': password,
print(await apiRequest(url, map));
final response = await apiRequest(url, map);
print(response);
List<Map> reply = json.decode(response);
List<UserModelData> result = reply.map((item) => new UserModelData.fromJson(item)).toList();
print(result[0].accessToken);
Future<String> apiRequest(String url, Map jsonMap) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('Accept', 'application/json');
request.headers.set('Content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
var reply = await response.transform(utf8.decoder).join();
httpClient.close();
print(reply);
return (reply);
This is the function for a login request in remote server. After Login json responses are decoded and stored in reply variable. Now i want to extract each elements like access_token , token_type... from the response. How can I do that ?
As the exception reads, you're problem is that you are casting a map into a list, which is not possible. Just as you can't cast a String to an integer or as you can't treat a rainworm as a horse and ride on it to the sunset.
The question of course is why that happens:
The line json.decode(response)
returns a map but the variable that you want to assign this map may only store a list.
For example, if your response looks something like this:
"body": [
"Alisa",
"Alex",
"Boby",
"Monica"
Then your json.decode(response)
is going to be Map<String, List>("body" to ["Alisa", ...])
, so body is mapped to the names.
Assuming that you want to isolate the list from the other json, you can just do json.decode(response).get("body")
or if youre json looks different, you can also get all values or keys in the map by calling json.decode(response).values()
or json.decode(response).keys()
.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.