Building a watch party app with Flutter alongside Ella
This is a blog on how to use Firebase to create a real time chat message
Hi everyone,
This is my note for the Flutterbyte Conference 2024.
started a series explaining how to integrate YouTube API in a Flutter watch party app. I will briefly explain how to use Firebase to create real-time messages and a chat room in an app.To build a Flutter chat application using Firebase with chat rooms and real-time messaging, you can use Firebase’s Firestore for data storage and Firebase Authentication for secure user management. Here's a guide with code samples for integrating these Firebase services into a Flutter project:
Set Up Firebase Project
In the Firebase Console, create a new project and add your app (iOS/Android).
Enable Firestore (recommended) or Realtime Database for storing chat data.
Enable Firebase Authentication to manage user sign-in.
Download the Firebase configuration file (google-services.json for Android, GoogleService-Info.plist for iOS) and add it to your Flutter project.
Add Firebase to Your Flutter Project
In your
pubspec.yaml
, add Firebase dependencies:
dependencies:
firebase_core: latest_version
firebase_auth: latest_version
cloud_firestore: latest_version
Initialize Firebase in your
main.dart
file
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
User Authentication
Use Firebase Authentication to register and log in users, enabling secure and user-associated messaging.
Example of a simple sign-up method:
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> signUp(String email, String password) async {
await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
}
Set Up Firestore for Messages and Chat Rooms
Design Firestore collections and subcollections for chat rooms and messages:
chatRooms (collection)
├── roomId (document)
│ ├── roomName: "Flutter Devs"
│ └── messages (subcollection)
│ ├── messageId (document)
│ │ ├── senderId: "user1"
│ │ ├── senderName: "John Doe"
│ │ ├── text: "Hello, everyone!"
│ │ └── timestamp: Timestamp
Create a New Chat Room
Add a chat room by creating a document in the chatRooms
collection
Future<void> createChatRoom(String roomName) async {
CollectionReference chatRooms = FirebaseFirestore.instance.collection('chatRooms');
await chatRooms.add({
'roomName': roomName,
'createdAt': FieldValue.serverTimestamp(),
});
}
Display Chat Rooms in Real-Time
Use
StreamBuilder
to list all chat rooms and enable users to navigate into a specific room:
StreamBuilder(
stream: FirebaseFirestore.instance.collection('chatRooms').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return ListView(
children: snapshot.data!.docs.map((doc) {
return ListTile(
title: Text(doc['roomName']),
onTap: () {
// Navigate to the chat room
Navigator.push(context, MaterialPageRoute(
builder: (context) => ChatRoomScreen(roomId: doc.id, roomName: doc['roomName']),
));
},
);
}).toList(),
);
},
);
Sending a Message in a Chat Room
Send a message by adding a document to the messages
subcollection:
Future<void> sendMessage(String roomId, String text) async {
CollectionReference messages = FirebaseFirestore.instance
.collection('chatRooms')
.doc(roomId)
.collection('messages');
await messages.add({
'text': text,
'senderId': FirebaseAuth.instance.currentUser?.uid,
'senderName': FirebaseAuth.instance.currentUser?.displayName,
'timestamp': FieldValue.serverTimestamp(),
});
}
Display Messages in Real-Time
Use a StreamBuilder
to show messages in a chat room, displaying them in real-time as they are added to Firestore
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('chatRooms')
.doc(roomId)
.collection('messages')
.orderBy('timestamp')
.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return ListView(
children: snapshot.data!.docs.map((doc) {
return ListTile(
title: Text(doc['senderName']),
subtitle: Text(doc['text']),
trailing: Text(doc['timestamp'].toDate().toString()),
);
}).toList(),
);
},
);
By following these steps and using the code provided, you can create a chat app that allows users to join different chat rooms, send messages in real-time, and see messages as they are added. This example builds a strong base for adding more features like user presence, typing indicators, or media sharing in future versions.
Thank you.
Love
Deborah.