如何将imagePath更改为文件?

问题描述

我拍摄了一张照片,并将其存储在一个临时目录中,因此可以在发布前在预览屏幕上对其进行查看。我试图弄清楚如何将该imagePath转换为文件,以便可以将其存储在Firebase中。

这是拍照功能

_onCapturePressed(context) async {
    // Take the Picture in a try / catch block. If anything goes wrong,// catch the error.
    try {
      // Attempt to take a picture and log where it's been saved
      final path = join(
        // In this example,store the picture in the temp directory. Find
        // the temp directory using the `path_provider` plugin.
        (await getTemporaryDirectory()).path,'${DateTime.now()}.png',);
      //print(path);
      await controller.takePicture(path);
      imagePath = path;

      // If the picture was taken,display it on a new screen
      Navigator.push(
        this.context,MaterialPageRoute(
          builder: (context) => displayStoryUploadScreen(),),);
    } catch (e) {
      // If an error occurs,log the error to the console.
      print(e);
    }
  }

这是用于预览图片的displayUploadScreen函数。

imageFile通过“ body:”传递

displayStoryUploadScreen() {
    print(imagePath);
    //Navigator.pop(context);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,iconTheme: IconThemeData(color: Colors.blue),title: Text(
          "Preview",style: TextStyle(
            color: Colors.blue,fontSize: 22.0,actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.done,color: Colors.blue,size: 30.0,onPressed: () => controlUploadAndSave(),],// The image is stored as a file on the device. Use the `Image.file`
      // constructor with the given path to display the image.
      body: Image.file(File(imagePath),//decoration: BoxDecoration(image: DecorationImage(image: FileImage(file),fit: BoxFit.cover)),);
  }

这是我需要帮助的保存功能。我需要将imagePath设置为文件,以便该部分正常工作,并且可以添加将照片保存到Firebase的逻辑。

controlUploadAndSave() async {
    setState(() {
      uploading = true;
    });

    await compressingPhoto();

    String downloadUrl = await uploadPhoto(file);

    savePostInfoToFireStore(url: downloadUrl);

    setState(() {
      file = null;
      uploading = false;
      storyPostId = Uuid().v4();
    });
  }

解决方法

您实际上已经做到了。使用File(path)从给定路径返回文件。

编辑:基于其他信息的更多详细信息:

您实际上应该使用更多的参数,而不是状态中的值,但这最终取决于您。基本上,您需要做的是将imagePath作为参数(如果不想在函数内进行转换,则将File(imagePath)传递给controlUploadAndSave

此外,您提到imagePath为空时遇到问题。当您将函数传递给页面路由时,我实际上不知道Flutter可以工作。这是不正常的,您应该创建小部件,而不是返回小部件的函数。但是,您也可以在此处将imagePath作为参数传递。

主要问题是您使用函数而不是小部件。您应该为新屏幕(ConfirmationScreen)具有一个单独的小部件(如果需要,则具有单独的状态)。然后,您可以使用类似的内容:

MaterialPageRoute(
  builder: (context) => ConfirmationScreen(imageFile: File(imagePath)),),

要将图像发送到此小部件。完成该屏幕的设置并想返回上一屏幕后,您只需弹出导航器并选择包含一个值即可。此值将作为将来返回到您称为Navigator.push的位置。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...