如何在抖动中设置拾取的图像

时间:2020-10-30 08:06:49

标签: image flutter

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

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"),

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

1 个答案:

答案 0 :(得分:0)

此代码非常含糊,不清楚您在哪里调用getImage以及在哪里设置图像。

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

无论如何,这里有一个正确的解释,它应该可以工作。

  • 在Widget类中声明您的getImage方法。
Future<File> getImage(int type) async {
   PickedFile pickedImage = await ImagePicker().getImage(
      source: type == 1 ? ImageSource.camera : 
      ImageSource.gallery,
      imageQuality: 50
    );
    return pickedImage;
  }
  • 在状态类中声明File状态变量
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"),