0
0
Fluttermobile~10 mins

Cloud Storage for files in Flutter

Choose your learning style9 modes available
Introduction

Cloud Storage lets your app save and get files like photos or documents online. This means users can access their files from any device.

You want users to upload profile pictures and save them safely.
Your app needs to store documents or reports that users can download later.
You want to back up app data like images or videos to the cloud automatically.
You want to share files between users through your app.
You want to save files without using the phone's local storage.
Syntax
Flutter
final storageRef = FirebaseStorage.instance.ref();

// Upload a file
await storageRef.child('folder/filename.jpg').putFile(file);

// Download a file URL
String url = await storageRef.child('folder/filename.jpg').getDownloadURL();

Use FirebaseStorage.instance.ref() to get the root reference.

Use child('path') to point to a file or folder.

Examples
Uploads a file named photo.png inside the images folder.
Flutter
final storageRef = FirebaseStorage.instance.ref();
await storageRef.child('images/photo.png').putFile(file);
Gets the download URL for report.pdf inside the docs folder.
Flutter
String url = await storageRef.child('docs/report.pdf').getDownloadURL();
Creates a reference to a folder user_uploads where you can add files.
Flutter
final folderRef = storageRef.child('user_uploads');
Sample App

This app lets the user pick an image from their gallery, uploads it to Firebase Cloud Storage, and then shows the download URL.

The image preview appears after selection, and the URL appears after upload.

Flutter
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);
      _downloadUrl = '';
    });

    final storageRef = FirebaseStorage.instance.ref();
    final fileRef = storageRef.child('uploads/${DateTime.now().millisecondsSinceEpoch}.png');

    await fileRef.putFile(_image!);
    final url = await fileRef.getDownloadURL();

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Cloud Storage Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _image == null ? Text('No image selected.') : Image.file(_image!, width: 150, 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', textAlign: TextAlign.center),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Make sure to initialize Firebase in your app before using Cloud Storage.

Use unique file names to avoid overwriting files.

Handle permissions to access gallery or camera on the device.

Summary

Cloud Storage lets apps save and get files online easily.

Use FirebaseStorage.instance.ref() to start working with files.

Upload files with putFile() and get URLs with getDownloadURL().