【问题标题】:Trying to get a data field from our Firestore database but the integer is returned as null试图从我们的 Firestore 数据库中获取数据字段,但整数返回为 null
【发布时间】:2025-12-28 19:45:14
【问题描述】:

我的代码中的方法应该为我们的调查移动应用程序获取问题所需的超时时间。然而,即使我们建立了一个应该保存数据副本的文档快照,该方法也只返回 null。我们有一个硬编码的后备,因此当超时为空时,它将返回一个默认小部件。

我们在小部件及其自身的方法中尝试了几种异步和等待,但似乎没有一个能够使小部件等待来自 firestore 文档的超时。

const fiveSeconds = Duration(seconds: 5);
Future<int> getTimeOutData() async{
  int toReturn;
  Firestore.instance.collection("config").getDocuments().then((DocumentSnapshot) async=>{
    Future.delayed(fiveSeconds, () async => toReturn = await DocumentSnapshot.documents[0]['timeout']),
    print( toReturn)
  });
  return toReturn;
}
Widget _buildListItem(BuildContext context, DocumentSnapshot doc) {
  return ListTile(
    title: Text(
      doc['question_text'].toString(),
      style: Theme.of(context).textTheme.headline,
    ),
    dense: true,
    trailing: Icon(Icons.keyboard_arrow_right),
    contentPadding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
    onTap: () async{
      timeout= await getTimeOutData();
      envelope = new Envelope(doc['complete'], doc.documentID, doc['user'],
          doc['question'], doc['answer_text'], doc['answer_type'], doc['time_stamp']);
       Navigator.push(
        context,
         MaterialPageRoute(
          builder: (context) {
            return ViewAnswerController(envelope,  timeout);
          },
        ),
      );
    },
    selected: true,
  );
}

我预计 1 毫秒,但实际值在方法内打印时为空,并且稍后在不同小部件中检查时为空。

【问题讨论】:

    标签: asynchronous flutter dart google-cloud-firestore widget


    【解决方案1】:
    const fiveSeconds = Duration(seconds: 5);
    Future<int> getTimeOutData() async{
      int toReturn;
      await Firestore.instance.collection("config").getDocuments().then((DocumentSnapshot) async=>{
        await Future.delayed(fiveSeconds, () async => toReturn = await DocumentSnapshot.documents[0]['timeout']),
        print( toReturn)
      });
      return toReturn;
    }
    

    没关系,我只是需要更多等待,因为 .then() 也是一个 Future 对象。

    【讨论】: