File 如何将imagePath更改为文件?

File 如何将imagePath更改为文件?,file,flutter,path,filepath,temporary-files,File,Flutter,Path,Filepath,Temporary Files,我拍了一张照片,它被存储在一个临时目录中,以便在发布之前可以在预览屏幕上查看。我正试图弄清楚如何将此imagePath转换为文件,以便将其存储在Firebase中 controlUploadAndSave() async { setState(() { uploading = true; }); await compressingPhoto(); String downloadUrl = await uploadPhoto(file);

我拍了一张照片,它被存储在一个临时目录中,以便在发布之前可以在预览屏幕上查看。我正试图弄清楚如何将此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();
    });
  }
这是拍照的功能

_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:”传递:


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

编辑:基于额外信息的更多详细信息:

你真的应该在你的状态中使用更多的参数,而不是值,但最终这取决于你。基本上,您需要做的是将
imagePath
作为参数(或者
文件(imagePath)
,如果您不想在函数中转换它)传递到
controlUploadAndSave

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

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

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

将图像发送到此小部件。完成该屏幕并希望返回到上一屏幕后,只需弹出导航器并可选地包含一个值。此值将作为将来返回到您调用的
Navigator.push

好的,那么我在controlUploadAndSave函数中做错了什么?文件在打印时为空。我想知道如何通过@davidh将文件传递给
controlUploadAndSave
函数?您是否在您的状态中使用变量?另外,在
body
中,您只需创建一个图像小部件。你从来没有把这个
文件保存到任何地方,这正是我需要帮助的地方。我不确定如何在预览屏幕上保存此文件并将其传递给controlUploadAndSave函数。但我只创建了图像小部件来查看它(以防您想返回并重新拍摄图片)。除非按下“保存”,否则我不想保存它。也许我认为逻辑是错误的,这是不可能的。更新了我的答案,提供了更多细节
MaterialPageRoute(
  builder: (context) => ConfirmationScreen(imageFile: File(imagePath)),
),