'chats not displaying in my streambuilder widget

im developing a chat app in flutter i've created a search funtion where users can search by name or email and send massage to them . but my problem is whenever i click at chat user it creats a chatroom where all massages should be . but when i send massage it displayes 0 massages , tho massages are there stored in my firestore database but unable to fetch them in my ui

here's my search.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:test_app/pages/chatroom.dart';
import 'package:test_app/pages/login.dart';

class search extends StatefulWidget {
  const search({Key? key}) : super(key: key);

  @override
  _searchState createState() => _searchState();
}

class _searchState extends State<search> {
  final TextEditingController _search = TextEditingController();
  final FirebaseAuth _auth = FirebaseAuth.instance;
  Map<String, dynamic>? userMap;
  bool isLoading = false;

  // chatroomid
  String chatRoomId(String user1, String user2) {
    if (user1[0].toLowerCase().codeUnits[0] >
        user2.toLowerCase().codeUnits[0]) {
      return "$user1$user2";
    } else {
      return "$user2$user1";
    }
  }

  onSearch() async {
    final aa = _auth.currentUser!.displayName!;
    if (aa.isEmpty) {
      print("is empty");
    } else {
      print(aa);
    }

    FirebaseFirestore _firestore = FirebaseFirestore.instance;
    setState(() {
      isLoading = true;
    });
    if (_search.text.contains("@")) {
      await _firestore
          .collection('users')
          .where("email", isEqualTo: _search.text)
          .get()
          .then((value) {
        setState(() {
          userMap = value.docs[0].data();
          isLoading = false;
        });
        print(userMap);
      });
    } else if (_search.text == "#dev_info") {
      Navigator.push(context, MaterialPageRoute(builder: (context) => Login()));
    } else {
      await _firestore
          .collection("users")
          .where("username", isGreaterThanOrEqualTo: _search.text)
          .get()
          .then((value) {
        setState(() {
          userMap = value.docs[0].data();
          isLoading = false;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      body: isLoading
          ? Center(
              child: Container(
                height: size.height / 20,
                width: size.height / 20,
                child: CircularProgressIndicator(),
              ),
            )
          : Column(children: [
              SizedBox(
                height: 45,
              ),
              Container(
                height: size.height / 14,
                width: size.width,
                alignment: Alignment.center,
                child: Container(
                  height: size.height / 14,
                  width: size.width / 1.15,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(32),
                  ),
                  child: TextFormField(
                    controller: _search,
                    decoration: InputDecoration(
                      hintStyle: TextStyle(fontSize: 17),
                      suffixIcon: Icon(
                        Icons.search,
                        color: Colors.black,
                      ),
                      contentPadding: EdgeInsets.all(18),
                      hintText: "search",
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(10.0)),
                          borderSide: BorderSide(
                              color: Color.fromARGB(255, 41, 40, 38))),
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 5,
              ),
              Container(
                alignment: Alignment.centerRight,
                height: size.height / 14,
                width: size.width / 1.15,
                child: ElevatedButton.icon(
                  onPressed: onSearch,
                  icon: const Icon(Icons.arrow_right_alt_rounded),
                  label: Text("search"),
                  style: ElevatedButton.styleFrom(
                    primary: Color.fromARGB(234, 47, 48, 48),
                  ),
                ),
              ),
              SizedBox(
                height: 15,
              ),
              userMap != null
                  ? PhysicalModel(
                      color: Color.fromARGB(255, 255, 254, 254),
                      elevation: 18,
                      shadowColor: Color.fromARGB(255, 75, 75, 73),
                      borderRadius: BorderRadius.circular(20),
                      child: ListTile(
                        tileColor:
                            Color.fromARGB(255, 255, 255, 255).withOpacity(0.5),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15),
                        ),
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(userMap!['photoUrl']),
                        ),
                        title: Text(
                          userMap!['username'],
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 17,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        subtitle: Text(userMap!['tag']),
                        trailing: IconButton(
                          onPressed: () {
                            String roomId = chatRoomId(
                                "dkjsdhksjdhskjdh",
                                userMap!['username']);
                            Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (_) => ChatRoom(
                                  chatRoomId: roomId,
                                  userMap: userMap!,
                                ),
                              ),
                            );
                          },
                          icon: Icon(Icons.photo),
                        ),
                      ),
                    )
                  : Container(),
                       
            ]),
    );
  }
}

here's my chatroom.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

class ChatRoom extends StatelessWidget {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  final TextEditingController _massage = TextEditingController();
  final Map<String, dynamic> userMap;
  final String chatRoomId;
  ChatRoom({required this.chatRoomId, required this.userMap});

  onSendMassage() async {
    if (_massage.text.isNotEmpty) {
      Map<String, dynamic> massages = {
        "sendby": _auth.currentUser!.displayName,
        "massage": _massage.text,
        "time": FieldValue.serverTimestamp(),
        "type": "text"
      };

      await _firestore
          .collection("chatroom")
          .doc(chatRoomId)
          .collection("chat")
          .add(massages);
      _massage.clear();
    } else {
      _firestore
          .collection('chatroom')
          .doc(chatRoomId)
          .collection('chats')
          .orderBy("time", descending: false)
          .snapshots();
      print("please input some massage");
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        leading: new Container(
          child: new IconButton(
            icon: new Icon(Icons.arrow_back_ios),
            onPressed: () {/* Your code */},
          ),
        ),
        title: Text('username'),
        backgroundColor: Colors.grey[850],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              height: size.height / 1.25,
              width: size.width,
              child: StreamBuilder<QuerySnapshot>(
                stream: _firestore
                    .collection('chatroom')
                    .doc(chatRoomId)
                    .collection('chats')
                    .orderBy("time", descending: false)
                    .snapshots(),
                builder: (BuildContext context,
                    AsyncSnapshot<QuerySnapshot> snapshot) {
                  if (snapshot.data != null) {
                    return ListView.builder(
                      itemCount: snapshot.data!.docs.length,
                      itemBuilder: (context, index) {
                        return Center(
                            child: Text(
                          snapshot.data!.docs[index]['massage'],
                        ));
                      },
                    );
                  } else {
                    return Container(
                      child: Center(
                        child: Text('data'),
                      ),
                    );
                  }
                },
              ),
            ),
            Container(
              height: size.height / 10,
              width: size.width,
              alignment: Alignment.center,
              child: Container(
                height: size.height / 12,
                width: size.width / 1.1,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    PhysicalModel(
                      color: Colors.white,
                      elevation: 42,
                      shadowColor: Color.fromARGB(255, 64, 64, 65),
                      borderRadius: BorderRadius.circular(20),
                      child: Container(
                        height: size.height / 16,
                        width: size.width / 1.3,
                        child: TextField(
                          controller: _massage,
                          decoration: InputDecoration(
                            contentPadding: const EdgeInsets.all(12),
                            border: InputBorder.none,
                            suffixIcon: IconButton(
                              onPressed: () {},
                              icon: Icon(Icons.photo),
                            ),
                            hintText: "Send Message",
                          ),
                        ),
                      ),
                    ),
                    IconButton(
                        icon: Icon(
                          Icons.arrow_circle_right_rounded,
                          size: 38,
                        ),
                        onPressed: onSendMassage),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
} 

its my school project i need to submit before monday im down to provide any information you need to solve this bug



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source