I am making a chat detail page using flutter. However, I am getting this error in the stream part. I don't have much experience with flutter. I couldn't solve it for 2 days.
Error :
Exception has occurred.
_AssertionError ('package:cloud_firestore_platform_interface/src/internal/pointer.dart': Failed assertion: line 56 pos 12: 'isDocument()': is not true.)
Code :
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_bubble/bubble_type.dart';
import 'package:flutter_chat_bubble/chat_bubble.dart';
import 'package:flutter_chat_bubble/clippers/chat_bubble_clipper_6.dart';
class Chat extends StatefulWidget {
Chat({super.key, required this.friendUid, required this.friendName});
final String friendUid;
final String friendName;
@override
State<Chat> createState() => _ChatState(friendUid, friendName);
}
class _ChatState extends State<Chat> {
CollectionReference chats = FirebaseFirestore.instance.collection("chats");
final friendUid;
final friendName;
final currentUserUid = FirebaseAuth.instance.currentUser!.uid;
var chatDocId;
var _controller = TextEditingController();
_ChatState(this.friendName, this.friendUid);
@override
void initState() {
chats
.where("users", isEqualTo: {friendUid: null, currentUserUid: null})
.limit(1)
.get()
.then(
(QuerySnapshot snapshotx) {
if (snapshotx.docs.isNotEmpty) {
chatDocId = snapshotx.docs.single.id;
} else {
chats.add({
"users": {currentUserUid: null, friendUid: null},
}).then((value) {
chatDocId = value;
});
}
},
)
.catchError(() {});
super.initState();
}
void sendMessage(String msg) {
if (msg == "") return;
chats.doc(chatDocId.toString()).collection("messages").add({
"createdOn": FieldValue.serverTimestamp(),
"uid": currentUserUid,
"msg": msg
}).then((value) {
_controller.text = "";
});
}
bool isSender(String friend) {
return friend == currentUserUid;
}
Alignment getAlignment(String friend) {
if (friend == currentUserUid) {
return Alignment.topRight;
}
return Alignment.topLeft;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("chat")),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: chats
.doc(chatDocId.toString())
.collection("messages") ==> the error part
.orderBy("createdOn", descending: true)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text("Error"),
);
}
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasData) {
return ListView(
reverse: true,
children: snapshot.data!.docs
.map((DocumentSnapshot documentSnapshot) {
Map<String, dynamic> data = documentSnapshot
.data() as Map<String, dynamic>;
return ChatBubble(
clipper: ChatBubbleClipper6(
nipSize: 0,
radius: 0,
type: isSender(data["uid"].toString())
? BubbleType.sendBubble
: BubbleType.receiverBubble),
alignment:
getAlignment(data["uid"].toString()),
margin: EdgeInsets.only(top: 20),
backGroundColor:
isSender(data["uid"].toString())
? Color(0xFF08C187)
: Color(0xffE7E7ED),
child: Container(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context)
.size
.width *
0.7),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Text(
data["msg"],
style: TextStyle(
color: isSender(
data["uid"]
.toString())
? Colors.white
: Colors.black),
maxLines: 100,
overflow:
TextOverflow.ellipsis,
)
],
)
],
)),
);
}).toList());
}
return Container(
width: 300,
height: 300,
color: Colors.grey,
);
})),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: TextField(
controller: _controller,
)),
IconButton(
onPressed: () {
sendMessage(_controller.text);
},
icon: Icon(Icons.send))
],
)
],
),
));
}
}
Can you help me. Thank you.
CodePudding user response:
The error is likely caused by the fact that the chatDocId variable is not initialized before it is used in the stream builder. In the initState method, the chatDocId variable is set inside a then block, which is executed asynchronously, so it might not be initialized when the stream builder is first rendered. To fix this, you can use the FutureBuilder widget to wait for the chatDocId variable to be initialized before rendering the stream builder.