Skip to content

Instantly share code, notes, and snippets.

@anoochit
Created August 13, 2022 05:34
Show Gist options
  • Select an option

  • Save anoochit/36f23da3fcf11e8f615bf160c02ed09e to your computer and use it in GitHub Desktop.

Select an option

Save anoochit/36f23da3fcf11e8f615bf160c02ed09e to your computer and use it in GitHub Desktop.
chat message page
// show chat screen
import 'dart:developer';
import 'package:chat/consts.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class ChatPage extends StatelessWidget {
ChatPage({Key? key, required this.roomId}) : super(key: key);
final String roomId;
final TextEditingController messageController = TextEditingController();
sendMessage({required String message}) {
if (message.trim().isNotEmpty) {
// save message to firestore
// chats/[ROOM-ID]/messages/[TIMESTAMP]/doc
final timeStamp = DateTime.now().millisecondsSinceEpoch.toString();
firestore.collection("chats").doc(roomId).collection("messages").doc(timeStamp).set({
'content': message.trim(),
'uid': auth.currentUser!.uid,
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
// chat message
Expanded(
child: StreamBuilder(
stream: firestore.collection("chats").doc(roomId).collection("messages").snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
// has error
if (snapshot.hasError) {
return Text("Error");
}
// has data
log('${snapshot.data!.docs.length}');
if (snapshot.hasData) {
final docs = snapshot.data!.docs;
return ListView.builder(
itemCount: docs.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(docs[index]["content"]),
);
},
);
}
// loading
return Center(child: CircularProgressIndicator());
},
),
),
// chat box
Container(
width: MediaQuery.of(context).size.width,
height: 64,
child: Row(
children: [
// text form field
Container(
width: MediaQuery.of(context).size.width - 48,
height: 64,
child: TextFormField(
controller: messageController,
onFieldSubmitted: (newValue) {
// send message
log('${newValue}');
sendMessage(message: newValue);
},
),
),
// icon button
IconButton(
onPressed: () {
// send message
log('${messageController.text}');
sendMessage(message: messageController.text);
},
icon: Icon(Icons.send),
),
],
),
)
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment