Series 1 of 2 — Part 3 of 5
Building a Flutter Shopping App — Part 3: Cloud Firestore and Push Notifications
Series: Building a Flutter Shopping App — From Zero to Architecture
By this point the app had a working UI, Riverpod state management, and Firebase Auth. The next step was connecting it to a real backend — Firestore for user data persistence and Firebase Cloud Messaging for push notifications.
Integrating Cloud Firestore
I added cloud_firestore to pubspec.yaml and updated the plugin registrations. I used Firestore to persist user profile data and cart items server-side. The data structure was a top-level users collection, keyed by Firebase Auth uid, with a cart subcollection.
await FirebaseFirestore.instance
.collection('users')
.doc(currentUser.uid)
.collection('cart')
.doc(product.id)
.set(cartItem.toJson());
One thing that caught me out was plugin registration. After adding Firestore and other Firebase plugins, I had to make sure they were all properly registered for both platforms. Missing a registration does not always throw an obvious error — sometimes it silently fails to initialise.
Setting up push notifications
I integrated both Firebase Cloud Messaging and flutter_local_notifications. FCM handles server-sent notifications. flutter_local_notifications handles displaying them when the app is in the foreground, since FCM does not show a notification UI when the app is active.
There are three scenarios to handle separately: app in foreground, app in background, and app terminated. Each has a different handler.
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// App foregrounded — show local notification
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// App backgrounded — user tapped notification
});
Saving and refreshing the FCM token
For targeted notifications you need the device's FCM token saved in Firestore. I fetched and saved it after every login, and set up a token refresh listener because FCM tokens can change. If you do not update the stored token when it refreshes, notifications will eventually stop delivering.
What I learned
- Verify plugin registration: Register all Firebase plugins explicitly — silent failures are harder to debug than crashes.
- Handle all notification states: Push notifications have three separate states (foreground, background, terminated) and each needs its own handler.
- Token lifecycle: Save and refresh FCM tokens on every login, not just the first one.
Next: Part 4 — The Big Refactor: Migrating to MVVM with Repositories and ViewModels
Top comments (0)