简体   繁体   English

dart 中的变量值更新 scope

[英]Variable value update scope in dart

    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?有没有办法解决这个问题?

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.没有更新的原因是,在 else 语句中,它被编写为进行 API 调用并更新名称,但在此之前执行下一行代码,因为我们不等待它完成。 To fix this you can add an await before the api call要解决此问题,您可以在 api 调用之前添加等待

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
      });

It is because the inner print(name) is printed after the http request is successfully made ie the then part of the http.get promise这是因为在成功发出http request后打印内部print(name)http.get promisethen部分

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而外部print(name)不等待http request完成要克服这个问题,您可以使用以下方法之一

To overcome this you can use either of 3 methods:为了克服这个问题,您可以使用以下 3 种方法之一:

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

The async/await is simple and preferred to be used, hence use the following code: async/await很简单,更适合使用,因此使用以下代码:

 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
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM