[英]Get one field from one document in Firestore
我想要我的 flutter 应用程序中当前登录用户的用户名。
这就是我目前所拥有的。
Future<String> get username async {
await FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.get()
.then((snapshot) {
if (snapshot.exists) {
return snapshot.data()!['username'].toString();
}
});
return 'No User';
}
它给了我“‘Future<String>’的实例。
弄清楚了...最终使用了这个。
FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
future: FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.get(),
builder: (_, snapshot) {
if (snapshot.hasData) {
var data = snapshot.data!.data();
var value = data!['username'];
return Text(value);
}
return const Text('User');
},
),
Future<String> get username
async {
await FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.get()
.then((snapshot) {
if (snapshot.exists) {
_user = snapshot.data['username'].toString();
return _user
}
});
return 'No User';
}
这是意料之中的。 由于您在 getter 实现中使用异步操作并且需要时间才能完成,因此无法立即返回字符串值。 由于无法阻止代码的执行(这会导致糟糕的用户体验),它现在只能返回Future<String>
:一个 object可能在某个时候产生一个字符串。
要从Future
获取值,您可以使用then
或await
。 后者最容易阅读,并且是:
print(await username);
使用then()
它看起来像这样:
username.then((value) {
print(value);
})
要了解有关在 Flutter/Dart 中处理异步行为的更多信息,请查看异步编程:futures、async、await 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.