我正在使用以下代码从图库中选择图像,然后上载到Flutter应用程序中的Firebase存储,但是我希望,如果用户未选择图像,则应将资产中的默认图像上载到Firebase存储中。我应该为要从资产中选择的图像编写什么代码,并将其设置为等于File avatarImageFile
,以便可以将其上传到Flutter应用程序中的Firebase存储中
File avatarImageFile;
Future getImage() async {
File image = await ImagePicker.pickImage(source: ImageSource.gallery);
if (image != null) {
setState(() {
avatarImageFile = image;
isLoading = true;
});
}
uploadFile();
}
答案 0 :(得分:5)
您可以将Asset图片转换为File,然后上传到Firebase! 这是要转换的代码:
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;
}
在您的示例中,您将这样调用此函数:
File f = await getImageFileFromAssets('images/myImage.jpg');
并编辑您的代码:
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();
}