Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting NULL value for async function (after using await) then updating to the new value

When I run my app it throws a lot of errors, and the red/yellow error screen on my device, which refreshes automatically and shows me the expected output then.

From the log I can see that first my object is return as null, which somehow later updates and I get the output.

I have recently started Android Dev (Flutter)

I tried to follow a number of online guides and also read related questions on async responses but no troubleshooting has been helping me. My biggest problem being that I can't figure out what exactly is the problem.

In my _AppState class:

  void initState() {
    super.initState();
    fetchData();
  }

  fetchData() async {
    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(() {});
  }

Expected output (Terminal):

Mumbai
Rain

Actual output (Terminal): https://gist.github.com/Purukitto/99ffe63666471e2bf1705cb357c2ea32 (Actual error was crossing the body limit of StackOverflow)

ScreenShots: At run initial After a few seconds

like image 244
Purukitto Avatar asked Aug 19 '19 06:08

Purukitto


People also ask

Does async await replace then?

The function loadJson becomes async . All .then inside are replaced with await . Then the outer code would have to await for that promise to resolve.

Does await return a value?

Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression.

Can I mix async await with then?

Yes, you can use mix await and then syntax - they both work on promises - but you shouldn't do so in the same function. But that's not the main issue in your code.

Does await unwrap a promise?

The await expression is usually used to unwrap promises by passing a Promise as the expression . This causes async function execution to pause until the promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.


1 Answers

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!

like image 86
thedarthcoder Avatar answered Sep 25 '22 00:09

thedarthcoder