Title: Building a Flutter Chat App with Firebase
Introduction
In today’s digital world, chat applications have become a necessity for communication. Flutter, combined with Firebase, provides an efficient way to build a real-time chat app with minimal effort. This blog post will guide you through the process of creating a chat application using Flutter and Firebase.
Prerequisites
Before starting, ensure you have the following:
Step 1: Setting Up Firebase
google-services.json
file for Android and GoogleService-Info.plist
for iOS.pubspec.yaml
file:dependencies:
firebase_core: latest_version
firebase_auth: latest_version
cloud_firestore: latest_version
main.dart
file:import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Step 2: Implementing User Authentication
Firebase Authentication allows users to sign in using email/password or Google Sign-In.
Future<User?> signInWithEmail(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
return userCredential.user;
} catch (e) {
print("Error: $e");
return null;
}
}
Step 3: Setting Up Firestore Database
Cloud Firestore stores and syncs messages in real time.
messages
collection to store chat messages.void sendMessage(String text, String userId) {
FirebaseFirestore.instance.collection('messages').add({
'text': text,
'senderId': userId,
'timestamp': FieldValue.serverTimestamp(),
});
}
Step 4: Displaying Messages in Real Time
Use StreamBuilder
to listen for new messages and display them in a chat UI.
StreamBuilder(
stream: FirebaseFirestore.instance.collection('messages').orderBy('timestamp').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
var messages = snapshot.data.docs;
return ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
return Text(messages[index]['text']);
},
);
},
);
Step 5: Creating a Chat UI
Use Flutter widgets like ListView
, TextField
, and FloatingActionButton
to create a user-friendly chat interface.
TextField(
controller: messageController,
decoration: InputDecoration(labelText: 'Enter message'),
);
FloatingActionButton(
onPressed: () {
sendMessage(messageController.text, currentUser.id);
},
child: Icon(Icons.send),
);
Conclusion
By integrating Firebase with Flutter, we have successfully created a real-time chat app. You can further enhance the app by adding features like image sharing, push notifications, and user profiles. Happy coding!
© 2025 Invastor. All Rights Reserved
User Comments