firebase 无法显示收到的消息

dbf7pr2w  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(151)

我无法显示我收到的消息,我正在使用firebase firestore。我试图获得所有的消息与流构建器和显示它。

流生成器类

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:instagram_clone/Models/user_model.dart';
import 'package:instagram_clone/Provider/user_provider.dart';
import 'package:instagram_clone/utils/circular_progress_indicator.dart';
import 'package:instagram_clone/utils/colors.dart';
import 'package:instagram_clone/utils/utils.dart';
import 'package:instagram_clone/widgets/message_bubbles.dart';
import 'package:provider/provider.dart';

import '../resources/Firestore_methods.dart';
class MessagesScreen extends StatefulWidget {
  String recieveruid;
  MessagesScreen({Key? key,required this.recieveruid}) : super(key: key);

  @override
  State<MessagesScreen> createState() => _MessagesScreenState();
}

class _MessagesScreenState extends State<MessagesScreen> {
  String recieverName=' ';
  String reciverDp=' ';
  bool isFetched=false;
  TextEditingController messagecontoller=TextEditingController();
  void sendMessage()async{
    if(messagecontoller.text.isNotEmpty){
      String res=await FireStoreMethods().sendMessage(
          senderUid: FirebaseAuth.instance.currentUser!.uid,
          recieverUid: widget.recieveruid,
          message: messagecontoller.text);
      if(res!='success'){
        Utils().showSnackBar(context, 'Unable to send message kindly check your connection', Colors.red);
      }
    }

  }
  void getRecieverDetails()async{
   DocumentSnapshot ref= await FirebaseFirestore.instance.collection('users').doc(widget.recieveruid).get();
   recieverName=ref['username'];
   reciverDp=ref['photourl'];
   setState(() {
     isFetched=true;
   });
  }
  @override
  void initState() {
    print(widget.recieveruid);
    getRecieverDetails();
    // TODO: implement initState
    super.initState();
  }
  @override
  void dispose() {
    messagecontoller.dispose();
    // TODO: implement dispose
    super.dispose();
  }
  bool _isReciever=true;
  @override
  Widget build(BuildContext context) {
    UserModel user=Provider.of<UserProvider>(context).getUser;
    return !isFetched?Center(child: CircularIndicator,):Scaffold(
      appBar: AppBar(
        title: Text(recieverName),
        backgroundColor: mobileBackgroundColor,
        centerTitle: true,
      ),
      body: Stack(
        children: [
          Container(
            height: MediaQuery.of(context).size.height*0.8,
            child: StreamBuilder(
               stream: FirebaseFirestore.instance
                   .collection('chats')
                   .where('senderuid',isEqualTo: FirebaseAuth.instance.currentUser!.uid )
                   .where('recieveruid',isEqualTo: widget.recieveruid)
                   .snapshots(),
                  builder: (context,AsyncSnapshot<QuerySnapshot<Map<String,dynamic>>>snapshot){
                 if(!snapshot.hasData || snapshot.connectionState==ConnectionState.waiting){
                   return Center(child: CircularIndicator);
                 }
                 else{
                   return ListView.builder(
                       itemCount: snapshot.data!.docs.length,
                       itemBuilder: (context,index){
                     if(snapshot.data!.docs[index]['senderuid']==FirebaseAuth.instance.currentUser!.uid){
                       return MessageBubbles(profilePic: user.photourl,
                           message: snapshot.data!.docs[index]['message'],
                           date: snapshot.data!.docs[index]['datetime'],
                           isReciever: false);
                     }
                     else{
                       return MessageBubbles(
                           profilePic: reciverDp,
                           message: snapshot.data!.docs[index]['message'],
                           date:snapshot.data!.docs[index]['datetime'],
                           isReciever: true);
                     }
                   });
                 }
            }
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,child: Container(
            child: Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: messagecontoller,
                    maxLines: null,
                    decoration: InputDecoration(
                        hintText: 'Message...',
                      contentPadding: EdgeInsets.symmetric(horizontal: 8),
                      border: InputBorder.none
                    ),
                  ),
                ),
                TextButton(onPressed: ()async{
                  sendMessage();
                  messagecontoller.clear();
                }, child: Text('Send',style: TextStyle(
                  color: Colors.blueAccent,
                  fontWeight: FontWeight.bold,
                  fontSize: 15
                ),))
              ],
            ),
            decoration: BoxDecoration(
              border: Border.all(color: secondaryColor),
              borderRadius: BorderRadius.circular(20),
              color: mobileBackgroundColor,
            ),
          ),),
        ],
      ),
    );
  }
}

这是消息气泡类

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../utils/colors.dart';
class MessageBubbles extends StatefulWidget {
  String profilePic;
  String message;
  final date;
  bool isReciever;
  MessageBubbles({Key? key,
  required this.profilePic,
    required this.message,
    required this.date,
    required this.isReciever
  }) : super(key: key);

  @override
  State<MessageBubbles> createState() => _MessageBubblesState();
}

class _MessageBubblesState extends State<MessageBubbles> {
  @override
  Widget build(BuildContext context) {
    return widget.isReciever?Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              CircleAvatar(
                backgroundImage: NetworkImage(widget.profilePic),
              ),
              FittedBox(
                child: Container(
                  width: MediaQuery.of(context).size.width*0.6,
                  constraints: BoxConstraints(
                      maxWidth: double.infinity,
                      maxHeight: double.infinity
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only
                      (topRight: Radius.circular(10),
                      bottomLeft: Radius.circular(10),
                      bottomRight: Radius.circular(10),
                    ),
                    color: Colors.grey.withOpacity(0.3),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Text(widget.message),
                  ),
                ),
              ),
              Text(DateFormat.yMMMd().format(widget.date.toDate()),style: TextStyle(
                  color: secondaryColor,
                  fontSize: 12
              ),),
            ],
          ),

        ],
      ),
    ):
    Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Text(DateFormat.yMMMd().format(widget.date.toDate()).toString(),style: TextStyle(
                  color: secondaryColor,
                  fontSize: 12
              ),),
              FittedBox(
                child: Container(
                  width: MediaQuery.of(context).size.width*0.6,
                  constraints: BoxConstraints(
                      maxWidth: double.infinity,
                      maxHeight: double.infinity
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only
                      (topRight: Radius.circular(10),
                      bottomLeft: Radius.circular(10),
                      topLeft: Radius.circular(10),
                    ),
                    color: Colors.blueAccent,
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Text(widget.message),
                  ),
                ),
              ),
              CircleAvatar(
                backgroundImage: NetworkImage(widget.profilePic),
              ),
            ],
          ),

        ],
      ),
    );
  }
}

这是输出片段

以下是firebase集合片段

inn6fuwd

inn6fuwd1#

  • 当前流的快照为接收方uid//发送方uid〉接收方uid〉快照()的列表类型
  • 并且您从senderuid的快照()中获取用户ID?感觉不对劲....
  • 我认为您应该为senderuid设置一个单独的侦听器

相关问题