-
Notifications
You must be signed in to change notification settings - Fork 2
Fetching Data from APIs in Dart
Abhinav Agrawal edited this page Mar 1, 2021
·
1 revision
To fetch data from an API you would be this code snippet:
void showStuff() async {
Map data = await getWeather(apiID,defaultCity);
print(data.toString());
}
Future<Map> getWeather(String apiId, String city) async {
String apiURL = 'https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiId&units=metric';
http.Response response = await http.get(apiURL);
print(json.decode(response.body));
return json.decode(response.body);
}Here we use a Weather API to send and receive weather data as a Response object in Dart.
The function returns the JSON as a Map object which is received in function showStuff() and response is loaded into data
If you notice that when you are fetching data, your code initially has nothing to render on the screen so you get a red error screen, now you need to build the data at runtime so that live data can be displayed to the User
We use FutureBuilder for this purpose.
Widget displayData()
{
return new FutureBuilder(future: getWeather(apiID, _cityEntered == null ? defaultCity : _cityEntered) ,
builder: (BuildContext context, AsyncSnapshot<Map> snapshot){
if(snapshot.hasData)
{
return ....
}
}
}Links :