【问题标题】:How to get a value outside of a .then()如何获取 .then() 之外的值
【发布时间】:2020-05-16 20:34:27
【问题描述】:

我需要检查 .then 函数内设置的变量的值,以便我可以返回不同的小部件,但我不知道。 在 then 之外,存在的值为 false,如果在 the 内部,则为 true。 另外,如果我将返回值放在 .then 中,则返回值为空。 你能帮帮我吗?

  Widget build(BuildContext context) {
     bool exists;

      seEsiste(db, idPaz).then((value) => {
       exists = value

    });

      if (exists) {
         return Text("load Text");
      }else {
           return ZefyrScaffold(
            child: ZefyrEditor(
              padding: EdgeInsets.all(16.0),
              controller: _controller,
              focusNode: _focusNode,
            ),
          );       
    }

  }
}

【问题讨论】:

  • 根据我的经验 - 只需将底部的所有内容都设置为 async 并在调用时将 await 放入,同时返回 .then 之前的部分。

标签: flutter async-await


【解决方案1】:

您应该将您的小部件更改为 StatefullWidget 并将您的代码更改为以下内容:

bool exists;

@override
void initState() {
  super.initState();
  seEsiste(db, idPaz).then((value) => {
   setState((){
     exists = value
   }
  });
}

Widget build(BuildContext context) {

      if (exists) {
         return Text("load Text");
      }else {
           return ZefyrScaffold(
            child: ZefyrEditor(
              padding: EdgeInsets.all(16.0),
              controller: _controller,
              focusNode: _focusNode,
            ),
          );       
      }

}

【讨论】:

    【解决方案2】:

    我刚刚使用 FutureBuilder 进行了修复

      Widget build(BuildContext context) {
    
    
       // var refertoRef = await Firestore.instance.collection("referto").document(idPaz).get();
    
        return FutureBuilder<bool>(
          future: seEsiste(db, idPaz),
          builder: (context, AsyncSnapshot<bool> snapshot) {
    
            if (snapshot.hasData){      
               if (snapshot.data)     {
                return Text("spetta un attimo");
               }else {
               return ZefyrScaffold(
                child: ZefyrEditor(
                  padding: EdgeInsets.all(16.0),
                  controller: _controller,
                  focusNode: _focusNode,
                ),
              );       
    
               }
    
            } else {
                return CircularProgressIndicator();
            }
          }
    
        );
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-17
      • 2018-02-18
      • 2021-11-09
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多