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

时间:2020-05-14 17:06:44

标签: 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,其下的代码也是如此。

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

请让我知道如何解决此问题,因为它使我发疯。预先感谢。

1 个答案:

答案 0 :(得分:2)

将方法更改为以下内容:

 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
}