How to upload image from assets in flutter to firebase storage?

1,825

You can convert Asset image to File then upload to Firebase! Here is code to convert:

import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';

Future<File> getImageFileFromAssets(String path) async {
  final byteData = await rootBundle.load('assets/$path');

  final file = File('${(await getTemporaryDirectory()).path}/$path');
  await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

  return file;
}

In your example, you would call this function like this:

File f = await getImageFileFromAssets('images/myImage.jpg');

and edit your code:

File avatarImageFile;

    Future getImage() async {
        File f = await getImageFileFromAssets('path of your asset Image');
        File image = await ImagePicker.pickImage(source: ImageSource.gallery);


      if (image != null) {
        setState(() {
          avatarImageFile = image;
          isLoading = true;
        });
      }else{
        avatarImageFile = f;
        isLoading = true;
      }

        uploadFile();
      }
Share:
1,825
Admin
Author by

Admin

Updated on December 21, 2022

Comments

  • Admin
    Admin over 1 year

    I am using below code to select image from gallery to upload to Firebase Storage in Flutter application, but I want that if the user doesn't select an image, a default image from the assets should be uploaded to the firebase storage. What code should I write for the image to be selected from assets and it is set equal to File avatarImageFile so that it can be uploaded to Firebase storage in flutter application

    File avatarImageFile;
        Future getImage() async {
            File image = await ImagePicker.pickImage(source: ImageSource.gallery);
    
            if (image != null) {
              setState(() {
                avatarImageFile = image;
                isLoading = true;
              });
            }
    
            uploadFile();
          }