Home > front end >  Variable value update scope in dart
Variable value update scope in dart

Time:08-07

    String name = "Jack";
    String aName = "John";
    if (!newChapter) {
       example....
    } else {
      http.get(Uri.parse("https://api.quran.com/api/v4/chapters/"   currentChapter)).then((result) {
        var results = json.decode(result.body);
        name = results["chapter"]["name_simple"];
        aName  = results["chapter"]["name_arabic"];
        print(name); // updated value


      });
 print(name); // default value: Jack
    }
 print(name); // default value: Jack

Why does the value isn't updated outside of the block? Is there a way to approach this?

CodePudding user response:

The reason why is not updated is that in the else statement it's written to make an API call and update the name but before this is complete the next line of code is executed since we are not awaiting it to complete. To fix this you can add an await before the api call

await http.get(Uri.parse("https://api.quran.com/api/v4/chapters/"   currentChapter)).then((result) {
        var results = json.decode(result.body);
        name = results["chapter"]["name_simple"];
        aName  = results["chapter"]["name_arabic"];
        print(name); // updated value
      });

CodePudding user response:

It is because the inner print(name) is printed after the http request is successfully made i.e the then part of the http.get promise

Whereas , the outer print(name) is not waiting for the http request to complete To overcome this you can use one of the following methods

To overcome this you can use either of 3 methods:

  1. callback function
  2. promise
  3. async/await

The async/await is simple and preferred to be used , hence use the following code:

 await http.get(Uri.parse("https://api.quran.com/api/v4/chapters/"   currentChapter)).then((result) {
        var results = json.decode(result.body);
        name = results["chapter"]["name_simple"];
        aName  = results["chapter"]["name_arabic"];
        print(name); // updated value
      });
  • Related