如何从flutter中的资产上传图像到firebase存储?

5hcedyr0  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(142)

我使用下面的代码从画廊中选择图像上传到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();
      }
osh3o9ms

osh3o9ms1#

您可以将资产图像转换为文件,然后上传到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();
      }

相关问题