Home > Mobile >  cannot display File? as image
cannot display File? as image

Time:11-13

I'm using imagepicker to capture an image, I've implemented sound null safety and I am passing it to a Second page but when trying to display image on 2nd page I'm getting error: The argument type 'File?' can't be assigned to the parameter type 'File'.

please assist, thank you :)

bellow are the code snippets

// 1st page : variable statements and getImage function

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

// 1st page: button executing the getImage function

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

// 2nd page class

class SecondPage extends StatefulWidget {
  File? image;

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

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

// in body of 2nd page where error is displayed

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

CodePudding user response:

The error you get came from null-safety, the type File? means that it could be either a File, or null, but your variable only accepts a File, and no null value.

For this, you can "force" the use of 'non-null' variable by adding a ! at the end of your variable, but be careful when doing this.

 Image.file(widget.image!),

You can learn more about null-safety syntax and principles on the official documentation: https://flutter.dev/docs/null-safety.

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

  • Related