【问题标题】:cannot display File? as image无法显示文件?作为图像
【发布时间】:2021-12-24 23:34:05
【问题描述】:

我正在使用 imagepicker 来捕获图像,我已经实现了健全的 null 安全性,并且我将它传递到第二页,但是当尝试在第二页上显示图像时出现错误: 参数类型“文件?”不能分配给参数类型“文件”。

请帮忙,谢谢:)

下面是代码sn-ps

// 第1页:变量语句和getImage函数

File? _image;
final _picker = ImagePicker();

Future getImage() async {
Map<Permission, PermissionStatus> statuses = await [
Permission.camera,
].request();

if (await Permission.camera.request().isGranted) {
PickedFile? _pickedFile = await _picker.getImage(
source: ImageSource.camera, maxHeight: 1920, maxWidth: 1080);
setState(() {
_image = File(_pickedFile!.path);
});
}}

//第一页:执行getImage函数的按钮

ElevatedButton(
                onPressed: () async {
                  await getImage();
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return SecondPage(image: _image);
                  })); //callback
                },

//第二页类

class SecondPage extends StatefulWidget {
  File? image;

  //c'tor
  SecondPage({
    Key? key,
    @required this.image,
  }) : super(key: key);

  @override
  _SecondPageState createState() => _SecondPageState();
}

// 在显示错误的第二页正文中

SizedBox(
          width: 300,
          height: 265,
          child:  Image.file(widget.image),
            ),

【问题讨论】:

    标签: flutter flutter-image flutter-file


    【解决方案1】:

    您得到的错误来自空安全,File? 类型意味着它可以是Filenull,但您的变量只接受File,没有null 值.

    为此,您可以通过在变量末尾添加 ! 来“强制”使用“非空”变量,但这样做时要小心。

     Image.file(widget.image!),
    

    您可以在官方文档中了解更多关于 null-safety 语法和原则的信息:https://flutter.dev/docs/null-safety

    https://api.flutter.dev/flutter/material/DropdownButton-class.html.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-29
      • 2017-02-19
      • 2017-05-13
      • 1970-01-01
      • 2012-08-30
      • 2016-03-12
      • 2013-12-31
      相关资源
      最近更新 更多