Reputation: 2101
List<String> getData() async {
var response = await http.get(url);
if (response.statusCode == 200) {
String data = response.body;
print(data);
var temperature = jsonDecode(data)['main']['temp'];
var condition = jsonDecode(data)['weather'][0]['id'];
var city_name = jsonDecode(data)['name'];
return [temperature, condition, city_name];
} else {
print(response.statusCode);
}
}
}
I get a strange error saying that I can't return List<String>
because is expecting List<String>
to be returned.
Upvotes: 5
Views: 38168
Reputation: 52494
As a generalization, when you get this error in an async function:
A value of type x can't be returned from method because it has a return type of x
The message seems weird, but it could mean that you are missing a Future<> return type.
So add Future<> to your method return type:
Example:
List<String> getValues() async
{
List<String> list = await getJson();
return list;
}
Change to:
Future<List<String>> getValues() async
{
List<String> list = await getJson();
return list;
}
Upvotes: 2
Reputation: 395
Since the function get data is is async it should return Future<List<String>>
example is as follows:
Future<List<String>> getData() async {
var response = await http.get(url);
if (response.statusCode == 200) {
String data = response.body;
print(data);
var temperature = jsonDecode(data)['main']['temp'];
var condition = jsonDecode(data)['weather'][0]['id'];
var city_name = jsonDecode(data)['name'];
return <String>[temperature, condition, city_name];
} else {
print(response.statusCode);
}
}
Also your are decoding 3 times unnecessarily, you can do it once keep it in var and use for further usage, example as follows:
String data = response.body;
var decodedData = jsonDecode(data);
var temperature = decodedData['main']['temp'];
var condition = decodedData['weather'][0]['id'];
var city_name = decodedData['name'];
Upvotes: 4