【问题标题】:How to upload pic from assets?如何从资产上传图片?
【发布时间】:2020-10-26 06:32:47
【问题描述】:

我正在使用下面的代码从画廊上传图片,如果没有从画廊中提取图片,我希望将来自 assets 的图片上传到 firebase 存储,因为 @987654322 @ 应该等同于资产中的图像文件。 我怎样才能做到这一点?

Future getImage() async {
    print("get image");

    PickedFile image = await _picker.getImage(source: ImageSource.gallery);

    if (image != null) {
      setState(() {
        final File file = File(image.path);
        avatarImageFile = file;
        isLoading = true;

      });
    }
    else{
      //if image is null then the image from the assets should be made picked into `avatarImageFile `

   }


  }

【问题讨论】:

    标签: flutter imagepicker


    【解决方案1】:

    在 Flutter 中,您可以通过两种方式加载资源:

    • 使用rootBundle.loadString("assets/my_file.json")加载文本文件

    • 使用rootBundle.load("assets/something.png") 加载任何类型的文件(图像、pdf 或任何其他类型的二进制文件)。

    请注意,load 也适用于 .json 文件,但通常在检索文本时 loadString 是更好的选择。欲了解更多信息,请阅读doc

    avatarImageFile = await rootBundle.load("assets/a/b/c.png");
    

    当你在小部件中时不要使用 rootBundle:相反,更喜欢使用DefaultAssetBundle

    class MyWidget extends StatelessWidget {
      const MyWidget();
    
      Future<String> loadConfig(BuildContext context) async =>
        await DefaultAssetBundle
        .of(context)
        .loadString("myassets/some_cfg.json");
    
      @override
      Widget build(BuildContext context) {...}
    
    }
    

    同样,当您在小部件中时执行上述操作。在任何其他情况下,请转到rootBundle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多