Home ¬Ľ How to Upload Image to Firebase Storage Flutter

How to Upload Image to Firebase Storage Flutter

With the Firebase Storage Flutter plugin, integrating Firebase Storage into Flutter apps is a breeze. This plugin allows programmers to easily use Flutter to upload, download, and manage files in Firebase Storage.

How to Upload Image to Firebase Storage Flutter4

 

Developers may store and retrieve user-generated content like audio recordings and profile images from anywhere with an internet connection. .

How to upload image to firebase storage flutter

To upload an image to Firebase Storage, check example below:

import 'dart:async';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:flutter/material.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:path_provider/path_provider.dart';
import 'DefaultFirebaseConfig.dart';
import 'dart:io' as io;
import 'package:http/http.dart' as http;

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseConfig.platformOptions);

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Row(children: [
            Image.asset(
              'assets/logo.png',
              height: 30,
            ),
            Text('flutterflux.com')
          ]),
        ),
        body: Container(
          child: FirebaseStorageExample(),
        ));
  }
}

class FirebaseStorageExample extends StatefulWidget {
  @override
  _FirebaseStorageExampleState createState() => _FirebaseStorageExampleState();
}

class _FirebaseStorageExampleState extends State {
  XFile? _imageFile;
  String? _downloadUrl;
  bool _downloading = false;
  Future _pickImage() async {
    final pickedFile =
        await ImagePicker().pickImage(source: ImageSource.gallery);
    setState(() {
      _imageFile = pickedFile;
    });
  }

  Future _uploadImage() async {
    FirebaseStorage storage = FirebaseStorage.instance;
    Reference ref = storage.ref().child('images/${_imageFile!.path}');
    TaskSnapshot task = await ref.putFile(io.File(_imageFile!.path));
    String downloadUrl = await task.ref.getDownloadURL();
    setState(() {
      _downloadUrl = downloadUrl;
    });
  }

  Future _downloadFile() async {
    setState(() {
      _downloading = true;
    });
    FirebaseStorage storage = FirebaseStorage.instance;
    Reference ref = storage.ref().child('images/$_downloadUrl');
    TaskSnapshot task = await ref.putFile(io.File(_imageFile!.path));
    String downloadUrl = await task.ref.getDownloadURL();
    setState(() {
      _downloadUrl = downloadUrl;
      _downloading = false;
    });
  }

  Future _openFile() async {
    if (_downloadUrl != null) {
      final response = await http.get(Uri.parse(_downloadUrl!));
      final tempDir = await getTemporaryDirectory();
      final file = File('${tempDir.path}');
      await file.writeAsBytes(response.bodyBytes);
      // Open the file using a suitable app
      // ...
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _imageFile != null
                ? Image.file(io.File(_imageFile!.path))
                : Text('No image selected'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _pickImage,
              child: Text('Select Image'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _uploadImage,
              child: Text('Upload Image'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _downloadFile,
              child: Text('Download File'),
            ),
            Text("download url:$_downloadUrl "),
            _downloading
                ? CircularProgressIndicator()
                : ElevatedButton(
                    onPressed: _openFile,
                    child: Text('Open File'),
                  ),
          ],
        ),
      ),
    ));
  }
}

This code establishes the parameters for a basic ImageUploader widget, which lets the user pick a picture from their local storage and send it to the server. Selecting an image file is handled by the ImagePicker package, and then the file is uploaded to FirebaseStorage via the Reference class and the _uploadImage() method.

See also  How to Add Firebase Flutter App

How to Upload Image to Firebase Storage Flutter

The uploaded image’s download URL is stored in the _downloadUrl variable, which is displayed to the user once the upload is complete.

How to Download image?

The FirebaseStorage class in the firebase storage package is what you need to Download a picture from Firebase Storage. File download example via Firebase Storage using the following code:

Future _downloadFile() async { setState(() { _downloading = true; }); FirebaseStorage storage = FirebaseStorage.instance; Reference ref = storage.ref().child('images/$_downloadUrl'); TaskSnapshot task = await ref.putFile(io.File(_imageFile!.path)); String downloadUrl = await task.ref.getDownloadURL(); setState(() { _downloadUrl = downloadUrl; _downloading = false; }); }

The Firebase Storage service is represented initially by an instance of the FirebaseStorage class. Then, we specify the file’s path using the child() method and create a Reference object that points to it.

Afterwards, we use the file’s download URL that we obtained from the getDownloadURL() method. A string that can be used to retrieve the file from Firebase Storage, a URL.

Finally, to download the file, we can utilize a network library like http or dio, using the download URL we obtained. It is essential to keep in mind that authentication with Firebase is necessary to access the storage bucket. To do so, you can use Firebase Authentication or generate a custom token to authenticate requests.

Conclusion

Flutter developers can take advantage of Firebase Storage’s simple API to easily upload and download files, as well as manage storage rules and permissions.¬†Overall, Firebase Storage is a great option for Flutter developers looking for a cloud storage solution that is easy to use, scalable, and offers robust features for managing files in their applications.

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top