最终图像文件=等待文件(路径);不创建文件

final imageFile = await File(path); doesn't create a file

我正在使用相机拍照并将照片保存在手机内存中以便稍后将其发送到 AWS。我可以拍照并且图片的路径在那里,但是我无法使用以下路径从路径创建文件:

final imageFile = await File(path);

为什么这里没有创建文件?我总是在调试控制台上得到 'Image file does not exist'。

    import 'dart:io';
    import 'package:camera/camera.dart';
    import 'package:flutter/material.dart';
    import 'package:path/path.dart';
    import 'package:path_provider/path_provider.dart';

    class CameraPage extends StatefulWidget {
      // 1
      final CameraDescription? camera;
      // 2
      final ValueChanged? didProvideImagePath;

      CameraPage({Key? key, this.camera, this.didProvideImagePath})
          : super(key: key);

      @override
      State<StatefulWidget> createState() => _CameraPageState();
    }

    class _CameraPageState extends State<CameraPage> {
      CameraController? _controller;
      Future<void>? _initializeControllerFuture;

      @override
      void initState() {
        super.initState();
        // 3
        _controller = CameraController(widget.camera!, ResolutionPreset.medium);
        _initializeControllerFuture = _controller?.initialize();
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: FutureBuilder<void>(
            future: _initializeControllerFuture,
            builder: (context, snapshot) {
              // 4
              if (snapshot.connectionState == ConnectionState.done) {
                return CameraPreview(this._controller!);
              } else {
                return Center(child: CircularProgressIndicator());
              }
            },
          ),
          // 5
          floatingActionButton: FloatingActionButton(
              child: Icon(Icons.camera), onPressed: _takePicture),
        );
      }

      // 6
      void _takePicture() async {
        try {
          await _initializeControllerFuture;

          final tmpDirectory = await getTemporaryDirectory();
          final filePath = '${DateTime.now().millisecondsSinceEpoch}.jpg';
          final path = join(tmpDirectory.path, filePath);

          await _controller?.takePicture();

          widget.didProvideImagePath!(path);

          final imageFile = await File(path);

          if (imageFile.existsSync())
            print('Image file exists');
          else
            print('Image file does not exist');
        } catch (e) {
          print(e);
        }
      }

      // 7
      @override
      void dispose() {
        _controller?.dispose();
        super.dispose();
      }
    }

takePicture 方法将 return 拍摄的图像作为 XFile,您可以使用 XFile 路径创建一个带有 taken 的文件图片路径如下代码。

  File? imageFile;
  XFile? xFile = await _controller?.takePicture();
  if (xFile != null) {
    imageFile = File(xFile.path);
  }

  if (imageFile != null && imageFile.existsSync()) {
    print('Image file exists');
  } else {
    print('Image file does not exist');
  }