首页 > 解决方案 > 为什么我会得到“未来”' 而不是函数中的返回值?

问题描述

我试图在我的函数中获取返回值,但输出是“未来的实例”而不是数据库中学校字段名称的值

         @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) 时,我都会从数据库中获取正确的值

标签: flutter

解决方案


声明getName()函数时,将返回类型指定为Future<String>,然后调用时getName(),需要等待结果,例如publisherSchool = await getName(widget.postInfo['publisher-Id'], 'school').toString();


推荐阅读