Как получить данные из другой коллекции в streambuilder - PullRequest
0 голосов
/ 18 апреля 2020

У меня возникла проблема, и я не могу ее решить, у меня есть коллекция "Посты", которая содержит сообщения пользователей, каждое сообщение содержит идентификатор владельца сообщения, и у меня есть еще одна коллекция с именем "пользователи", и у каждого пользователя есть его имя и фотография, я хочу, чтобы имя пользователя и изображение отображались в его сообщении.

Коллекция сообщений enter image description here

Коллекция пользователей enter image description here

Я видел эту статью , но мне это не помогло, возможно, потому что я новичок.

Мой код:

StreamBuilder(
                  stream: Firestore.instance
                      .collection('Posts')
                      .orderBy('date', descending: true)
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      const Text('Loading...');
                    } else {
                      return ListView.builder(
                          physics:
                          NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          scrollDirection: Axis.vertical,
                          itemCount: snapshot
                              .data.documents.length,
                          itemBuilder: (context, index) {
                            DocumentSnapshot mypost =
                            snapshot
                                .data.documents[index];

                            return Stack(
                              children: <Widget>[
                                Container(
                                  decoration:
                                  BoxDecoration(
                                    borderRadius:
                                    BorderRadius
                                        .circular(
                                        15.0),
                                  ),
                                  child: Padding(
                                    padding:
                                    EdgeInsets
                                        .all(8.0),
                                    child: Column(
                                      children: <
                                          Widget>[
                                        InkWell(
                                          child: Row(
                                            children: <
                                                Widget>[
                                              Container(
                                                  width:
                                                  32.0,
                                                  height:
                                                  32.0,
                                                  decoration: BoxDecoration(shape: BoxShape.circle, image: DecorationImage(fit: BoxFit.fill, image: NetworkImage(
                                                    // user image url
                                                      'Owner of post img')))),
                                              SizedBox(
                                                width:
                                                10.0,
                                              ),
                                              Text(
                                                'Owner of post Name',
                                                style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 12.0,
                                                    fontWeight: FontWeight.bold,
                                                    fontFamily: 'BalooDa2'),
                                              ),
                                            ],
                                          ),
                                        ),
                                        Padding(
                                          padding:
                                          EdgeInsets.all(
                                              5.0),
                                          child: Text(
                                              '${mypost['text']}',
                                              style: TextStyle(
                                                  color: Colors
                                                      .white,
                                                  fontSize:
                                                  16.0,
                                                  fontFamily:
                                                  'Tajawal',
                                                  height:
                                                  1.3),
                                              textAlign:
                                              TextAlign
                                                  .justify,
                                              textDirection:
                                              TextDirection.rtl),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            );
                          });
                    }
                    return Container(
                      height: 0.0,
                      width: 0.0,
                    );
                  },
                ),

1 Ответ

1 голос
/ 18 апреля 2020

Вы можете использовать вложенные StreamBuilders для извлечения сведений о пользователе из идентификатора пользователя, который вы получаете из коллекции публикаций. Я добавил запрос, который будет соответствовать идентификатору пользователя из данных постов и поиска документов в коллекции пользователей, где идентификатор идентификатора пользователя равен идентификатору пользователя из постов. коллекция.

StreamBuilder(
        stream: Firestore.instance
            .collection('Posts')
            .orderBy('date', descending: true)
            .snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            const Text('Loading...');
          } else {
            return ListView.builder(
                physics:
                NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                scrollDirection: Axis.vertical,
                itemCount: snapshot
                    .data.documents.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot mypost =
                  snapshot
                      .data.documents[index];

                  return Stack(
                    children: <Widget>[
                      Container(
                        decoration:
                        BoxDecoration(
                          borderRadius:
                          BorderRadius
                              .circular(
                              15.0),
                        ),
                        child: Padding(
                          padding:
                          EdgeInsets
                              .all(8.0),
                          child: Column(
                            children: <
                                Widget>[
                              StreamBuilder(
                                stream: Firestore.instance
                                    .collection('users')
                                    .where('uid', isEqualTo: mypost['uid'])
                                    .snapshots(),
                                builder: (context, snapshot){
                                  switch (snapshot.connectionState) {
                                    case ConnectionState.waiting:
                                      return SizedBox();
                                    case ConnectionState.active:
                                    default:
                                      break;
                                  }
                                  if (snapshot.hasError) print(snapshot.error);
                                  DocumentSnapshot user = snapshot.data.documents[0];

                                  return  InkWell(
                                    child: Row(
                                      children: <
                                          Widget>[
                                        Container(
                                            width:
                                            32.0,
                                            height:
                                            32.0,
                                            decoration: BoxDecoration(shape: BoxShape.circle, image: DecorationImage(fit: BoxFit.fill, image: NetworkImage(
                                              // user image url
                                                '${user['uimg']}')))),
                                        SizedBox(
                                          width:
                                          10.0,
                                        ),
                                        Text(
                                          '${user['name']}',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 12.0,
                                              fontWeight: FontWeight.bold,
                                              fontFamily: 'BalooDa2'),
                                        ),
                                      ],
                                    ),
                                  );
                                },

                              ),
                              Padding(
                                padding:
                                EdgeInsets.all(
                                    5.0),
                                child: Text(
                                    '${mypost['text']}',
                                    style: TextStyle(
                                        color: Colors
                                            .white,
                                        fontSize:
                                        16.0,
                                        fontFamily:
                                        'Tajawal',
                                        height:
                                        1.3),
                                    textAlign:
                                    TextAlign
                                        .justify,
                                    textDirection:
                                    TextDirection.rtl),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  );
                });
          }
          return Container(
            height: 0.0,
            width: 0.0,
          );
        },
      ),
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...