flutter 如何在聊天应用程序的Dart中返回来自Future的字符串< String>?

yuvru6vn  于 2023-05-29  发布在  Flutter
关注(0)|答案(2)|浏览(132)

在一个聊天应用程序中,我试图查询Firestore,并从“联系人”集合中返回其他用户的名字作为字符串。我仍然在尝试在dart中理解async和Futures,所以当我返回这个时,它会打印'Instance of Future'而不是findName应该查询的字符串。

return ListView(
                    children: List.generate(_conversations.length, (i) {
                      

                      DocumentReference? _conversationRef =
                          _conversations[i].reference;
                      Map _conversation = _conversations[i].data() ?? {};


                      String otherUser = _conversation["members"][0] != uid
                          ? _conversation["members"][0]
                          : _conversation["members"][1];


                      Future<String> findName(otherUser) async {
                        var recipName = await FirebaseFirestore.instance
                            .collection("contacts")
                            .where("phone_number", isEqualTo: otherUser)
                            .get().then(

                              (querySnapshot) {
                                 for (var docSnapshot in querySnapshot.docs) {

                                   return docSnapshot.data()['full_name'].toString();
                                 }
                              });

                            if (recipName != null) {
                              return recipName;
                            } else {
                              return otherUser;
                            }
                      }

                      
                      contactName() async {
                        var name = await findName(otherUser);
                        return name.toString();
                      }

                      return ConversationTile(
                          conversationReference: _conversationRef,
                          otherUserId: contactName() ?? "user number");
                    }),
ltskdhd1

ltskdhd11#

如果你正在构建一个未来的UI,你想使用FutureBuilder,它可以控制未来结果的状态,并在未来完成后渲染UI。下面是一个简单的FutureBuilder示例,如果需要,我可以提供更多细节。

FutureBuilder(
 future: getMessages(),
 builder:(context, snapshot) {
  if (snapshot.hasData) { // Future Complete 
   return ListView.builder(itemBuilder:(context, index) {
    //build listview 
   },);
  }
 },
 return Center(child: CircularProgressIndicator()); // Future Not Complete / No Data
),
j8yoct9x

j8yoct9x2#

在Dart中,你可以通过使用async和await关键字从Future返回一个String。点击此链接https://dart.dev/codelabs/async-await
在您的情况下,更新的代码将是-

return ListView(
  children: List.generate(_conversations.length, (i) {
    DocumentReference? _conversationRef = _conversations[i].reference;
    Map _conversation = _conversations[i].data() ?? {};

    String otherUser = _conversation["members"][0] != uid
        ? _conversation["members"][0]
        : _conversation["members"][1];

    Future<String> findName(String otherUser) async {
      var querySnapshot = await FirebaseFirestore.instance
          .collection("contacts")
          .where("phone_number", isEqualTo: otherUser)
          .get();

      for (var docSnapshot in querySnapshot.docs) {
        return docSnapshot.data()['full_name'].toString();
      }

      return otherUser;
    }

    return FutureBuilder<String>(
      future: findName(otherUser),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return ConversationTile(
            conversationReference: _conversationRef,
            otherUserId: snapshot.data!,
          );
        } else if (snapshot.hasError) {
          return Text("Error: ${snapshot.error}");
        } else {
          return CircularProgressIndicator();
        }
      },
    );
  }),
);

相关问题