firebase - 无法从Firebase返回查询的数据(Flutter/Dart)

标签 firebase flutter dart google-cloud-firestore

上下文:我正在尝试从Firebase查询并返回字符串(imgUrl)。我始终能够在查询中打印字符串,但是返回的值始终为null。我想知道我的查询是否错误,并且不确定什么是最佳做法。

数据库概述:
enter image description here
查询功能:
这是我们DatabaseService()类下的代码,其中包含所有数据库查询和更新功能。

String getImageUrl(String _uid) {
    String _imgUrl;

    Firestore.instance
        .document('users/$_uid')
        .get()
        .then((value) => _imgUrl = value['imgUrl']);

    return _imgUrl;
  }

主要:
getImageUrl()在setImage()下调用。 setImage下的Toast始终返回null,其下的代码也返回null。

String _uid;

// Sets variable '_uid' to the uid of the current user
// Gets called in initstate
Future _getUid() async {
     FirebaseUser user = await FirebaseAuth.instance.currentUser();
     _uid = user.uid;
}

// Sets the profile photo. If there is no existing profile photo online,
// grab the image on the device. If there is no image online OR on the device,
// Display the default image
void setImage(String url) {
     // Get the url that's stored in the db
     String _tempUrl = DatabaseService().getImageUrl(_uid); // always ends up being null
     Fluttertoast.showToast(msg: "_tempUrl: $_tempUrl");

     // Rest of the function
}

@override
void initState() {
     super.initState();
     _getUid();
}

请让我知道该怎么做才能解决此问题,因为它使我发疯。提前致谢。

最佳答案

将方法更改为以下内容:

 Future<String> getImageUrl(String _uid) async {
    String _imgUrl;

    DocumentSnapshot value =
        await Firestore.instance.document('users/$_uid').get();
    _imgUrl = value['imgUrl'];
    return _imgUrl;
  }

使用async / await等待将来完成,然后像下面这样调用它:
  void setImage(String url) async{
     // Get the url that's stored in the db
     String _tempUrl = await DatabaseService().getImageUrl(_uid); // always ends up being null
     Fluttertoast.showToast(msg: "_tempUrl: $_tempUrl");

     // Rest of the function
}

关于firebase - 无法从Firebase返回查询的数据(Flutter/Dart),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61803237/

相关文章:

javascript - Firebase 规则 - 只读查询中的值

dart - Navigator routes 清除flutter的堆栈

flutter - 如何在flutter中固定SSL证书的公钥?

android - FirebaseAuth.getInstance() 总是返回 null

javascript - FCM 推送通知在本地工作,但不在服务器上工作

Firebase 函数仅授权来自 Firebase 托管应用的请求

flutter - 动画按钮旋转

flutter - 如何在 Flutter 中创建居中且大小相等的选项卡,Tab Bar

Flutter - Android 原生平台集成

angular - Dart Angular示例