Как реализовать экран, который показывает всех пользователей, которых я отправляю и отправляю мне сообщения, используя Flutter и Cloud Firestore - PullRequest
0 голосов
/ 16 июня 2020

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

Вкратце, я хотел бы реализовать экран, который показывает всех пользователей, которых я отправляю, и отправляю мне сообщения с помощью Flutter и Cloud Firestore.

Надеюсь, это имеет смысл.

См. Мой список пользователей в чате ниже:

На этом этапе я смог показать всех пользователей из моей базы данных (users), когда я выбираю пользователя из списка, он выводит меня на экран чата, однако реализация, которую я хочу, - это показывать только пользователей, которым я отправлял сообщения, и пользователей, которые отправляли мне сообщения .

import 'dart:convert';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:reviu/chat_manager/chat.dart';
import 'package:reviu/utilities/utilities_constants.dart';

class ListChatScreen extends StatefulWidget {
  final String currentUserId;
  final String peerId;
  ListChatScreen({Key key, this.currentUserId, this.peerId}) : super(key: key);

  @override
  State createState() => ListChatScreenState(currentUserId: currentUserId);
}

class ListChatScreenState extends State<ListChatScreen> {
  ListChatScreenState({Key key, @required this.currentUserId});

  //TODO 76 Instances and variables
  final String currentUserId;
  final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  final GoogleSignIn googleSignIn = GoogleSignIn();
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    registerNotification();
    configLocalNotification();
  }

  void registerNotification() {
    print('i am called');
    firebaseMessaging.requestNotificationPermissions();
    firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) {
        print('onMessage: $message');
        Platform.isAndroid
            ? showNotification(message['notification'])
            : showNotification(message['aps']['alert']);
        return;
      },
      onResume: (Map<String, dynamic> message) {
        print('onResume: $message');
        return;
      },
      onLaunch: (Map<String, dynamic> message) {
        print('onLaunch: $message');
        return;
      },
    );

    firebaseMessaging.getToken().then(
      (token) {
        print('token: $token');
        Firestore.instance
            .collection('users')
            .document(widget.currentUserId)
            .updateData({'pushToken': token});
      },
    ).catchError(
      (err) {
        Fluttertoast.showToast(msg: err.message.toString());
      },
    );
  }

  void configLocalNotification() {
    var initializationSettingsAndroid =
        new AndroidInitializationSettings('app_icon');
    var initializationSettingsIOS = new IOSInitializationSettings();
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  void showNotification(message) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      Platform.isAndroid
          ? 'com.dfa.flutterchatdemo'
          : 'com.duytq.flutterchatdemo',
      'Flutter chat demo',
      'your channel description',
      playSound: true,
      enableVibration: true,
      importance: Importance.Max,
      priority: Priority.High,
    );
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);

    print(message);
    print(message['body'].toString());
    print(json.encode(message));

    await flutterLocalNotificationsPlugin.show(0, message['title'].toString(),
        message['body'].toString(), platformChannelSpecifics,
        payload: json.encode(message));

    await flutterLocalNotificationsPlugin.show(
        0, 'plain title', 'plain body', platformChannelSpecifics,
        payload: 'item x');
  }

  Widget buildItems(BuildContext context, DocumentSnapshot document) {
    if (document['id'] == currentUserId) {
      return Container();
    } else {
      return Container(
        child: FlatButton(
          child: Row(
            children: <Widget>[
              Material(
                child: document['profileImageUrl'] != null
                    ? CachedNetworkImage(
                        placeholder: (context, url) => Icon(
                          Icons.account_circle,
                          size: 50.0,
                          color: themeColor,
                        ),
                        imageUrl: document['profileImageUrl'],
                        width: 50.0,
                        height: 50.0,
                        fit: BoxFit.cover,
                      )
                    : Icon(
                        Icons.account_circle,
                        size: 50.0,
                        color: themeColor,
                      ),
                borderRadius: BorderRadius.all(Radius.circular(25.0)),
                clipBehavior: Clip.hardEdge,
              ),
              Flexible(
                child: Container(
                  child: Column(
                    children: <Widget>[
                      Container(
                        child: Text(
                          '${document['nickname']}',
                          style: TextStyle(color: primaryColor),
                        ),
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.fromLTRB(5.0, 0.0, 0.0, 5.0),
                      ),
                    ],
                  ),
                  margin: EdgeInsets.only(left: 2.0),
                ),
              ),
            ],
          ),
          onPressed: () {
            print(document.documentID);
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => Chat(
                  peerId: document.documentID,
                  peerAvatar: document['profileImageUrl'],
                ),
              ),
            );
          },
          color: Colors.amberAccent[300],
          padding: EdgeInsets.fromLTRB(5.0, 10.0, 25.0, 10.0),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
        ),
        margin: EdgeInsets.only(bottom: 10.0, left: 0.0, right: 0.0),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            child: StreamBuilder(
              stream: Firestore.instance.collection('users').snapshots(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(themeColor),
                    ),
                  );
                } else {
                  return ListView.builder(
                    padding: EdgeInsets.all(10.0),
                    itemBuilder: (context, index) =>
                        buildItems(context, snapshot.data.documents[index]),
                    itemCount: snapshot.data.documents.length,
                  );
                }
              },
            ),
          ),
          Positioned(
            child: isLoading
                ? Container(
                    child: Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(greyColor),
                      ),
                    ),
                    color: Colors.white.withOpacity(0.8),
                  )
                : Container(),
          )
        ],
      ),
    );
  }
}

> Это база данных

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...