Флаттер, как я могу получить информацию о пользователе и отобразить ее на определенных c сообщениях в блоге из firestore? - PullRequest
0 голосов
/ 07 апреля 2020

Я новичок в дартс и флаттер с java (android). У меня есть список постов, которые публикуются разными пользователями. Я хочу отображать имя пользователя и изображение пользователя для каждого сообщения. Проблема в том, что я храню пользователей в коллекции «Users», а записи в коллекции «Posts». У меня есть идентификатор пользователя, прикрепленный к каждому сообщению, и я могу получить его (идентификатор) вместе с деталями сообщения. Но я не могу использовать его (идентификатор) для отображения информации профиля. Пожалуйста, помогите, некоторые строки кода, чтобы дать мне немного света будет высоко ценится. Ниже приведен мой код для отображения сообщений:

body: StreamBuilder(
        stream: Firestore.instance.collection('Posts').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            const Text('Loading...');
          } else {
            return ListView.builder(
              itemCount: snapshot.data.documents.length,
              itemBuilder: (context, index) {
                DocumentSnapshot myPosts = snapshot.data.documents[index];

                return Container(
                  width: MediaQuery.of(context).size.width,
                  //height: 350,
                  child: Padding(
                    padding: EdgeInsets.only(bottom: 8.0),
                    child: Center(
                      child: Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                CircleAvatar(
                                  radius: 20.0,
                                  backgroundColor: Colors.blueGrey,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: Container(
                                    color: Colors.black45,
                                    height: 30,
                                    width: 2,
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        'user name',
                                        style: TextStyle(
                                          fontSize: 16.0,
                                          fontWeight: FontWeight.bold,
                                          color: Colors.black54,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      Text(
                                        'user status',
                                        style: TextStyle(
                                          color: Colors.grey,
                                          fontSize: 14.0,
                                        ),
                                      )
                                    ],
                                  ),
                                )
                              ],
                            ),
                            SizedBox(
                              height: 10.0,
                            ),
                            Container(
                              width: MediaQuery.of(context).size.width,
                              //height: 200.0,
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(8.0),
                                child: AspectRatio(
                                  aspectRatio: 16 / 9,
                                  child: FadeInImage.assetNetwork(
                                    width: MediaQuery.of(context).size.width,
                                    placeholder: 'assets/images/loading.jpg',
                                    image: '${myPosts['post_image']}',
                                    fit: BoxFit.fill,
                                  ),
                                ),
                              ),
                            ),
                            SizedBox(
                              height: 10.0,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Flexible(
                                  child: Padding(
                                    padding: const EdgeInsets.only(right: 8.0),
                                    child: Text(
                                      '${myPosts['post_title']}',
                                      style: TextStyle(
                                        fontSize: 18.0,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.black87,
                                      ),
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ),
                                FlatButton(
                                  child: Text(
                                    'Download Pdf',
                                    style: TextStyle(
                                      fontSize: 14.0,
                                      color: Colors.black54,
                                    ),
                                  ),
                                  shape: OutlineInputBorder(
                                    borderSide: BorderSide(
                                        color: Colors.black54, width: 1),
                                    borderRadius: BorderRadius.circular(5),
                                  ),
                                  padding: const EdgeInsets.fromLTRB(
                                    15.0,
                                    4.0,
                                    15.0,
                                    4.0,
                                  ),
                                  onPressed: () {},
                                ),
                              ],
                            ),
                            SizedBox(
                              height: 10.0,
                            ),
                            Text(
                              '${myPosts['post_body']}',
                              style: TextStyle(
                                fontSize: 16.0,
                              ),
                              overflow: TextOverflow.ellipsis,
                              maxLines: 8,
                            ),
                            SizedBox(
                              height: 10.0,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(
                                    'Posted ' +
                                        TimeAgo.getTimeAgo(
                                            myPosts['post_time']),
                                    style: TextStyle(color: Colors.grey)),
                                Text(
                                    '${myPosts['comments_count']} Comment(s)',
                                    style: TextStyle(color: Colors.grey)),
                              ],
                            ),
                            SizedBox(
                              height: 10.0,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                );
              },
            );
          }
          return Loading();
        },
      ),

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

import 'package:cloud_firestore/cloud_firestore.dart';

class ProfileService {
  getProfileInfo(String uid) {
    return Firestore.instance
        .collection('Users')
        .where('user_id', isEqualTo: uid)
        .getDocuments();
  }
}

Ваша помощь будет высоко оценена. Я застрял.

1 Ответ

0 голосов
/ 07 апреля 2020

попробуйте использовать это:

Future<DocumentSnapshot> _getDocument(String uid) async {
 return await Firestore().collection('Users').where('user_id', isEqualTo: uid).get();
}

он вернет вам снимок документа, который затем вы можете использовать для получения информации о пользователе

...