Flutter:如何合并两个 StreamBuilder 并在卡片中显示输出

标签 flutter dart google-cloud-firestore

我有点坚持我正在尝试做的事情。我正在尝试合并我的两个 Stream Builder 以将输出显示为卡片中的一个。在我的第一个 StreamBuilder 中,我得到了一些用户信息,比如他发布的信息,他们需要什么。在我的第二个 StreamBuilder 中,我得到了他/她的名字,这样的联系人。可以合并为一个吗?所以我也会把数据作为一个。

这就是我使用 StreamBuilders 的方式。

第一个流:

StreamBuilder<QuerySnapshot>(
  stream: db.collection('HELP REQUEST').where('Type_OfDisaster', isEqualTo: '[Drought]').snapshots(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Column(
        children: snapshot.data.documents
          .map((doc) => buildItem(doc))
          .toList()
      );
    } else {
      return Container(
        child: Center(
          child: CircularProgressIndicator()
        )
      );
    }
  }
);

第二流:
StreamBuilder<QuerySnapshot>(
  stream: db.collection('USERS').where('User_ID', isEqualTo: widget.Uid).snapshots(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Column(
        children: snapshot.data.documents
          .map((doc) => buildItem(doc))
          .toList()
      );
    } else {
      return Container(
        child: Center(
          child: CircularProgressIndicator()
        )
      );
    }
  }
);

这是我输出在流构建器中获得的数据的地方:
Container buildItem(DocumentSnapshot doc) {
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;
return Container(
  child: Card(
    elevation: 5,
    child: Padding(
      padding: const EdgeInsets.only(top: 20, left: 20, right: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                children: <Widget>[
                  CircleAvatar(
                    radius: 30,
                    backgroundColor: Colors.black,
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Text('Name: '),
                  Text(
                    '${doc.data['Name_ofUser']}',
                    style: TextStyle(
                        fontSize: 15, fontWeight: FontWeight.w500),
                  )
                ],
              ),
            ],
          ),
          Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  height: 20,
                ),
                Row(
                  children: <Widget>[
                    Text('Date:'),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        '${doc.data['Help_DatePosted']}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 15, fontWeight: FontWeight.w500),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: <Widget>[
                    Text('Location:'),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        '${doc.data['Help_Location']}',
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.w500),
                      ),
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Text('Description:'),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    '${doc.data['Help_Description']}',
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        fontSize: 20, fontWeight: FontWeight.w500),
                  ),
                ),
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 10),
                child: Container(
                  height: _height * 0.05,
                  width: _width * 0.20,
                  child: FlatButton(
                    shape: RoundedRectangleBorder(
                        borderRadius:
                        BorderRadius.all(Radius.circular(20.0))),
                    color: Color(0xFF121A21),
                    onPressed: () {
                      _viewingRequest(doc.data);
                    },
                    child: Text(
                      'View',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.w800),
                    ),
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    ),
  ),
 );
}   

有可能做到吗?请帮我。

最佳答案

您可以在不直接使用 StreamBuilder 的情况下收听快照,如下所示:

List<HelpRequestsPlusUsers> helpRequestsPlusUsers = [];
List<User> allUsers = [];
List<HelpRequest> helpRequests = [];

@override
void initState() {
  db.collection('USERS').where('User_ID', isEqualTo: widget.Uid).snapshots().listen((snapshot){
    allusers = snapshot.data.documents;
    mergeUsersWithHelpRequests();
  });
  db.collection('HELP REQUEST').where('Type_OfDisaster', isEqualTo: '[Drought]').snapshots().listen((snapshot){
    helpRequests = snapshot.data.documents;
    mergeUsersWithHelpRequests();
  });
  super.initState();
}

void mergeUsersWithHelpRequests(){
  // Run the code to merge your allUsers and helpRequests data into a helpRequestsPlusUsers List
}

小工具
 Widget _buildHelpRequestsPlusUsersWidget (){
   if (helpRequestsPlusUsers.isNotEmpty) {
     return ListView.builder(
       itemBuilder: (context, index){
         return buildItem(helpRequestsPlusUsers[index]);
       }
     );
   } else {
     return Container(
       child: Center(
         child: CircularProgressIndicator()
       )
     );
   }
 }

关于Flutter:如何合并两个 StreamBuilder 并在卡片中显示输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59732692/

相关文章:

flutter - 创建Json数组并使用SharedPreferences列出

java - Android 上的 Flutter VoIP 推送通知

flutter - 抽象类不能被实例化!在身份验证 block 中

flutter - 如何检查滚动位置是在 ListView 的顶部还是底部?

firebase - 错误: Could not load the default credentials (Firebase function to firestore)

firebase - 在 Firebase Cloud 函数中获取请求 URL

java - 如何从 Firestore 获取数组?

flutter - 在 flutter 中将数据持久化/存储在 GetXController 中的正确方法

android - Flutter:尝试在 Android 上使用 map_view 显示交互式 map 时应用程序崩溃

android - Flutter 修复 FlatButton 中不同图片大小相同的问题