Home > Software design >  Flutter Expected a value of type 'int', but got one of type 'String'
Flutter Expected a value of type 'int', but got one of type 'String'

Time:11-17

I want to get the image link from the API that saved in "message" but I keep getting the same exception.

How can i get "message" and why it throws me this Exception.

My API

{"message":"https:\/\/images.dog.ceo\/breeds\/sheepdog-english\/n02105641_277.jpg","status":"success"}


API LINK: https://dog.ceo/api/breeds/image/random

My Method

Future<void> loadDog() async {

try {
  final response =
    await http.get(Uri.parse("https://dog.ceo/api/breeds/image/random"));
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    extractedData.forEach((id, data) {
      print(data["message"].toString());
    });
 } catch (err) {
print("ERROR = "   err.toString());
}

MY ERROR

ERROR = Expected a value of type 'int', but got one of type 'String'

CodePudding user response:

Here is my guess as to what is happening and how to fix it:

extractedData.forEach((id, data) {
      print(data["message"].toString());
});

The lines above is saying, for every key (id) and value (data) on my map, print the value's message property as a string, data will have the following values each iteration of the for each loop:

extractedData['message']
extractedData['status']

which means that what you are trying to print will be equal to:

extractedData['message']['message']

and

extractedData['status']['message']

neither of which exists.

In order to fix this, simply ditch the for-each loop:

print(extractedData['message']);

or if you want to use the for each-loop, you can print all values:

extractedData.foreach((key, value) {
  print('$key -> $value');
});

which should print

message -> https://images.dog.ceo/breeds/sheepdog-english/n02105641_277.jpg
status -> success
  • Related