The async
and await
is a mechanism for handling Asynchronous programming in Dart.
Asynchronous operations let your program complete work while waiting
for another operation to finish.
So whenever a method is marked as async
, your program does not pause for completion of the method and just assumes that it will complete at some point in the future.
Example: Incorrectly using an asynchronous function
The following example shows the wrong way to use an asynchronous function getUserOrder()
.
String createOrderMessage () {
var order = getUserOrder();
return 'Your order is: $order';
}
Future<String> getUserOrder() {
// Imagine that this function is more complex and slow
return Future.delayed(Duration(seconds: 4), () => 'Large Latte');
}
main () {
print(createOrderMessage());
}
If you run the above program it will produce the below output -
Your order is: Instance of '_Future<String>'
This is because, since the return type of the method is marked as Future, the program will treat is as an asynchronous method.
To get the user’s order, createOrderMessage()
should call getUserOrder()
and wait for it to finish. Because createOrderMessage()
does not wait for getUserOrder()
to finish, createOrderMessage()
fails to get the string value that getUserOrder()
eventually provides.
Async and await
The async and await keywords provide a declarative way to define asynchronous functions and use their results.
So whenever you declare a function to be async
, you can use the keyword await
before any method call which will force the program to not proceed further until the method has completed.
Case in point
In your case, the fetchData()
function is marked as async
and you are using await
to wait for the network calls to complete.
But here fetchData()
has a return type of Future<void>
and hence when you call the method inside initState()
you have to do so without using async/ await
since initState()
cannot be marked async
.
So the program does not wait for completion of the fetchData()
method as a whole and tries to display data which is essentially null
.
And since you call setState()
after the data is loaded inside fetchData()
, the screen refreshes and you can see the details after some time.
Hence the red and yellow screen error.
Solution
The solution to this problem is you can show a loading indicator on the screen until the data is loaded completely.
You can use a bool
variable and change the UI depending the value of that variable.
Example -
class _MyHomePageState extends State<MyHomePage> {
bool isLoading = false;
void initState() {
super.initState();
fetchData();
}
fetchData() async {
setState(() {
isLoading = true; //Data is loading
});
var cityUrl = "http://ip-api.com/json/";
var cityRes = await http.get(cityUrl);
var cityDecodedJson = jsonDecode(cityRes.body);
weatherCity = WeatherCity.fromJson(cityDecodedJson);
print(weatherCity.city);
var weatherUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + weatherCity.city + "," +
weatherCity.countryCode +
"&appid=" +
//Calling open weather map's API key from apikey.dart
weatherKey;
var res = await http.get(weatherUrl);
var decodedJson = jsonDecode(res.body);
weatherData = WeatherData.fromJson(decodedJson);
print(weatherData.weather[0].main);
setState(() {
isLoading = false; //Data has loaded
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: isLoading ? Center(child : CircularProgressIndicator())
: Container(), //Replace this line with your actual UI code
);
}
}
Hope this helps!
fetchData
function is async so it doesn't stop the widget from building. And when it builds first, theweatherData
is null. But after some time the API call gives some response and then you call setState and this time it works because nowweatherData
is not null. – Belak