Reputation:
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();
}
Upvotes: 5
Views: 3136
Reputation: 143
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();
}
Upvotes: 6