flutter - 为什么我会得到“未来”' 而不是函数中的返回值?
问题描述
我试图在我的函数中获取返回值,但输出是“未来的实例”而不是数据库中学校字段名称的值
@override
void initState() {
userId = _auth.currentUser!.uid;
publisherSchool =
getName(widget.postInfo['publisher-Id'], 'school').toString();
super.initState();
}
Future getName(String publisherUid, String fieldname) async {
DocumentSnapshot publisherSnapshot = await FirebaseFirestore.instance
.collection('users')
.doc(publisherUid)
.get();
print(publisherSnapshot.get(fieldname));
return publisherSnapshot.get(fieldname);
}
但是每当我打印 publisherSnapshop.get(fieldname) 时,我都会从数据库中获取正确的值
解决方案
声明getName()
函数时,将返回类型指定为Future<String>
,然后调用时getName()
,需要等待结果,例如publisherSchool = await getName(widget.postInfo['publisher-Id'], 'school').toString();
推荐阅读
- sql - Replace 00 with varbinary type
- gtk - GtkApplicationWindow 子类“销毁”两次
- php - PHP替换动态变量
- angularjs-directive - ng-selected 所需的验证不适用于复选框
- mysql - 使用左连接和分组方式重命名查询中的重复结果
- azure - 在 Azure 中的 dockerised App Service 上运行“安装”命令
- regex - 为什么匹配对象 .Value 没有按预期工作?
- php - 通过 php 处理并发 puppeteer 请求
- angular - Angular 4:在表单中添加/删除动态输入字段
- java - Sort stream of objects and get first and print out