Flutter 参数类型“文件?” 无法分配给参数类型“文件”

ram*_*han 5 dart flutter

我正在使用图像选择器,我需要将图像存储在文件中以便可以显示。

我正在这样做

  final ImagePicker _picker = ImagePicker();
  PickedFile? _imageFile;
File? imageFile;


  _imgFromCamera() async {
    final pickedFile =
        await _picker.getImage(source: ImageSource.camera, imageQuality: 50);

    setState(() {
      _imageFile = pickedFile;
          imageFile = File(pickedFile!.path);

    });
  }

  _imgFromGallery() async {
    final pickedFile =
        await _picker.getImage(source: ImageSource.gallery, imageQuality: 50);

    setState(() {
      _imageFile = pickedFile;
      imageFile = File(pickedFile!.path);

    });
  }
Run Code Online (Sandbox Code Playgroud)

但当我展示这个时

    Image.file(
        imageFile,
        width: 100,
        height: 100,
        fit: BoxFit.fitHeight,
      )
Run Code Online (Sandbox Code Playgroud)

它显示了这个错误 Flutter The argument type 'File?' can't be assigned to the parameter type 'File'。如果我?从文件中删除,那么它会显示一些空安全错误。

Tir*_*tel 0

Image.file需要 a File,而不是 a File?。使用三元运算符来渲染Image.file

imageFile != null ? Image.file(
  imageFile!,
  width: 100,
  height: 100,
  fit: BoxFit.fitHeight,
) : Text('imageFile is null'),
Run Code Online (Sandbox Code Playgroud)