Learn/Firebase Integration/Firebase Storage & Notifications

Firebase Storage & Notifications

Upload files to Cloud Storage and send push notifications

7 min~5 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Media And Notification Architecture
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Firebase Storage & Push Notifications

Firebase Cloud Storage allows your app to upload and download user-generated files such as profile pictures, videos, documents, and any other binary data. Files are stored in Google Cloud Storage buckets and can be accessed via secure download URLs that you save in Firestore. Firebase Cloud Messaging (FCM) is the push notification service that lets you send messages to individual devices or groups of users. Push notifications are essential for keeping users engaged by alerting them about new messages, updates, promotions, or important events even when the app is closed.

dart
1// ── CLOUD STORAGE ──
2// pubspec.yaml: firebase_storage: ^11.5.0
3import 'package:firebase_storage/firebase_storage.dart';
4import 'dart:io';
5
6final storage = FirebaseStorage.instance;
7
8// Upload a file
9Future<String> uploadImage(File file) async {
10 final ref = storage.ref().child('images/${DateTime.now().millisecondsSinceEpoch}.jpg');
11
12 final uploadTask = ref.putFile(file);
13
14 // Track progress
15 uploadTask.snapshotEvents.listen((event) {
16 final progress = event.bytesTransferred / event.totalBytes;
17 print('Upload: ${(progress * 100).toStringAsFixed(0)}%');
18 });
19
20 await uploadTask;
21 final downloadUrl = await ref.getDownloadURL();
22 return downloadUrl; // Store this URL in Firestore
23}
24
25// Delete a file
26await storage.ref().child('images/photo.jpg').delete();
dart
1// ── PUSH NOTIFICATIONS (FCM) ──
2// pubspec.yaml: firebase_messaging: ^14.7.0
3import 'package:firebase_messaging/firebase_messaging.dart';
4
5final messaging = FirebaseMessaging.instance;
6
7// Request permission (iOS)
8await messaging.requestPermission(
9 alert: true,
10 badge: true,
11 sound: true,
12);
13
14// Get device token (send to your server)
15final token = await messaging.getToken();
16print('FCM Token: $token');
17
18// Handle foreground messages
19FirebaseMessaging.onMessage.listen((RemoteMessage message) {
20 print('Title: ${message.notification?.title}');
21 print('Body: ${message.notification?.body}');
22 // Show local notification
23});
24
25// Handle notification tap (app in background)
26FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
27 // Navigate to specific screen
28 print('Notification tapped: ${message.data}');
29});

Background Messages

💡 Background Messages

For background message handling, define a top-level function annotated with @pragma(vm:entry-point) that takes a RemoteMessage parameter and calls Firebase.initializeApp() inside it. Register this handler using FirebaseMessaging.onBackgroundMessage(yourHandler). The function must be top-level (not inside a class) because the OS runs it in a separate isolate when the app is in the background.

Media And Notification Architecture

Treat uploads and notifications as one coordinated user flow:

  • Upload media and store resulting download URL in Firestore document metadata.
  • Trigger notification from trusted backend logic when document state changes.
  • Keep message payload minimal and fetch heavy data after app opens.
  • Define deep-link routes so notification tap lands users on the exact context.

This sequence avoids broken links, stale payloads, and confusing notification behavior.

Storage And FCM Failure States

  • Upload starts on cellular and network drops before completion.
  • Storage rules reject upload due to missing auth or invalid file path.
  • Device token rotates and backend keeps sending to old token.
  • Foreground notification arrives but local UI presentation is missing.
  • User taps notification after related content was deleted or archived.

Delivery Checklist For Media And Push

  • Upload progress, success, and failure states are clear in UI.
  • Storage paths and metadata conventions are documented and consistent.
  • FCM token registration refresh logic runs on app startup and token change.
  • Notification tap routing works from foreground, background, and terminated states.
  • Permission denial path is handled gracefully with re-enable guidance.

This Lesson In Simple Words

Upload files to Cloud Storage and send push notifications. Backend integration connects app actions to real user data and secure business workflows.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Define data model and access rules before writing convenience helper methods.

Deep Understanding Guide

Why this lesson matters

Security and data integrity issues can damage user trust faster than UI bugs.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Think from both sides: client UX and backend authorization constraints.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Trusting client-side checks without enforcing server-side rules.
  • Using broad read/write permissions in Firestore rules.
  • Storing secrets in plain text or unsafe local storage.
  • Not versioning schemas when documents evolve over time.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write one secure Firestore rule and test allow/deny cases.
  • Map one backend document model to a typed client model.
  • Implement auth-state based screen routing with guarded actions.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "How do you get the download URL after uploading a file?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • context: A handle to widget location and inherited data in the tree.
  • route: A screen entry managed by the Navigator.
  • firestore: A cloud NoSQL database used by Firebase apps.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Security rules are part of architecture, not optional deployment polish.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Firebase Storage & Notifications" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Trusting client-side checks without enforcing server-side rules.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

How do you get the download URL after uploading a file?

After uploading, call getDownloadURL() on the storage reference to get the public URL.

Which stream handles push notifications when the app is in the FOREGROUND?

FirebaseMessaging.onMessage fires when a notification arrives while the app is in the foreground.

What is the FCM token used for?

The FCM token uniquely identifies a device so your server can send push notifications to it.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue