【问题标题】:Flutter The argument type 'File?' can't be assigned to the parameter type 'File'Flutter 参数类型“文件?”不能分配给参数类型“文件”
【发布时间】:2021-08-08 10:26:42
【问题描述】:

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

我就是这样的

  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);

    });
  }

但是当我展示这个时

    Image.file(
        imageFile,
        width: 100,
        height: 100,
        fit: BoxFit.fitHeight,
      )

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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

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

    【讨论】:

    【解决方案2】:

    将文件初始化为新的文件对象。 改变这个

    File? imageFile;
    

    File imageFile=new File('');
    

    【讨论】:

      猜你喜欢
      • 2022-06-19
      • 2022-01-14
      • 2020-07-08
      • 2020-01-23
      • 2021-12-22
      • 2022-01-23
      • 2021-10-17
      • 2019-11-17
      • 2021-07-06
      相关资源
      最近更新 更多