首页 > 解决方案 > 如何在颤动中设置拾取的图像

问题描述

我尝试使用它来挑选和保存图像->

File imageFile;

Future getImage(int type) async {
   PickedFile pickedImage = await ImagePicker().getImage(
    source: type == 1 ? ImageSource.camera : 
  ImageSource.gallery,
      imageQuality: 50
);

if (pickedImage == null) return;

File tmpFile = File(pickedImage.path);
tmpFile = await tmpFile.copy(tmpFile.path);

   setState(() {
    imageFile = tmpFile;
      });
    }


 imageFile != null
              ? Image.file(
            imageFile,
            height: MediaQuery.of(context).size.height / 5,
          )
              : Text("Pick up the image"),

但是,图像没有保存。什么都没有显示。我还需要做什么?

标签: imageflutter

解决方案


这段代码非常模棱两可,非常不清楚您在哪里调用getImage以及在哪里设置图像。

我想你没有正确调用 getImage() 并且不确定你在哪里使用if (pickedImage == null) return;它可能是错误的。

无论如何,这是一个正确的解释,它应该有效。

  • getImage在 Widget 类中声明您的方法。
Future<File> getImage(int type) async {
   PickedFile pickedImage = await ImagePicker().getImage(
      source: type == 1 ? ImageSource.camera : 
      ImageSource.gallery,
      imageQuality: 50
    );
    return pickedImage;
  }
  • File在sate类中声明状态变量
File imageFile;
  • 在您的小部件中有一个Button用于选择图像的操作。
...
   IconButton(
     icon: Icon(Icons.gallery),
     onPressed: () {}
   )
...
  • 在处理程序中调用getImage方法和setState结果onPressed
...
   IconButton(
     icon: Icon(Icons.gallery),
     onPressed: () async {
      final tmpFile = await getImage(1);
       
        setState(() {
          imageFile = tmpFile;
      });
   )
...

  • 在小部件中显示您的文件
 imageFile != null
           ?Image.file(
            imageFile,
            height: MediaQuery.of(context).size.height / 5,
          ): Text("Pick up the image"),

推荐阅读