0
0
FlutterHow-ToBeginner · 4 min read

How to Use Firebase Storage in Flutter: Simple Guide

To use Firebase Storage in Flutter, first add the firebase_storage package and initialize Firebase. Then, upload or download files by calling methods like putFile() for uploads and getDownloadURL() to get file URLs.
📐

Syntax

Firebase Storage in Flutter uses the firebase_storage package. You create a reference to a storage location, then use methods to upload or download files.

  • FirebaseStorage.instance.ref(): Gets a reference to the root storage.
  • ref.child('path'): Points to a specific folder or file.
  • putFile(file): Uploads a file.
  • getDownloadURL(): Gets the URL to access the uploaded file.
dart
final storageRef = FirebaseStorage.instance.ref();
final imagesRef = storageRef.child('images');
final fileRef = imagesRef.child('myphoto.jpg');

// Upload a file
await fileRef.putFile(file);

// Get download URL
String url = await fileRef.getDownloadURL();
💻

Example

This example shows how to upload an image file picked from the device and then get its download URL.

dart
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  File? _image;
  String _downloadURL = '';

  Future<void> _pickAndUploadImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickedFile == null) return;

    setState(() {
      _image = File(pickedFile.path);
    });

    final storageRef = FirebaseStorage.instance.ref().child('uploads/${DateTime.now().millisecondsSinceEpoch}.jpg');
    await storageRef.putFile(_image!);
    final url = await storageRef.getDownloadURL();

    setState(() {
      _downloadURL = url;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Firebase Storage Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _image == null ? Text('No image selected.') : Image.file(_image!, height: 150),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _pickAndUploadImage,
                child: Text('Pick and Upload Image'),
              ),
              SizedBox(height: 20),
              _downloadURL.isEmpty ? Container() : SelectableText('Download URL:\n$_downloadURL')
            ],
          ),
        ),
      ),
    );
  }
}
Output
App with a button 'Pick and Upload Image'. When pressed, it opens gallery to pick an image, uploads it to Firebase Storage, then shows the image and its download URL below.
⚠️

Common Pitfalls

  • Not initializing Firebase before using Firebase Storage causes errors.
  • Forgetting to add firebase_storage and related dependencies in pubspec.yaml.
  • Using wrong file paths or references leads to upload/download failures.
  • Not handling permissions for file access on device.
  • Ignoring async/await can cause unexpected behavior.
dart
/* Wrong: Not awaiting upload */
storageRef.putFile(file);

/* Right: Await upload to complete */
await storageRef.putFile(file);
📊

Quick Reference

Here is a quick summary of key Firebase Storage methods in Flutter:

MethodDescription
FirebaseStorage.instance.ref()Get root storage reference
ref.child('path')Navigate to folder or file
putFile(File file)Upload a file
getDownloadURL()Get URL to access file
delete()Delete a file from storage

Key Takeaways

Always initialize Firebase before using Firebase Storage in Flutter.
Use FirebaseStorage.instance.ref() to get storage references and navigate with child().
Upload files with putFile() and get their URLs with getDownloadURL().
Handle async calls properly with await to avoid errors.
Check device permissions and add necessary dependencies in pubspec.yaml.