5

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();
      }

1 Answer 1

6

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();
      }
Sign up to request clarification or add additional context in comments.

1 Comment

Getting Error. Any solution please: PathNotFoundException: Cannot open file, path = '/data/user/0/com.example.t_store/cache/icons/categories/icons8-bowling-64.png' (OS Error: No such file or directory, errno = 2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.