Failed assertion: line 854 pos 14: 'file != null': is not true

Viewed 2361

I'm trying to display an image using FileImage() but it's throwing the "'file != null': is not true" error. The image is coming from an Image Picker function. The wierd thing is that, I know that the file exists because when I try to print it, it shows me the path for the file.

EDIT: Here's the link to the entire code if you need to check it: https://github.com/MBanawa/ecommerce_app/blob/master/lib/Admin/uploadItems.dart

Below is the function for the ImagePicker with a print method:

File imageFile;    
pickImage(ImageSource imageSource) async {
 Navigator.pop(context);
 final pickedFile = await ImagePicker().getImage(source: imageSource);
 setState(() {
   imageFile = File(pickedFile.path);
   print('Path $imageFile');
 });
}

I trigger the function in an onPressed() by either camera or gallery :

camera:

onPressed: () => pickImage(ImageSource.camera),

gallery

onPressed: () => pickImage(ImageSource.gallery),

Below is how I call the imageFile:

Container(
        height: 230.0,
        width: MediaQuery.of(context).size.width * 0.8,
        child: Center(
          child: AspectRatio(
            aspectRatio: 16 / 9,
            child: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: FileImage(imageFile),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
        ),
      ),

The container above is inside a function called displayAdminUploadFormScreen() that gets called if imageFile is not null. I place that after the build method of my statefulwidget state:

@override
Widget build(BuildContext context) {
   return imageFile == null
    ? displayAdminHomeScreen()
    : displayAdminUploadFormScreen();
}

What I'm confused about is that, print() returns an actual link after taking a picture. here is a sample result when taking a picture using the camera:

I/flutter (16227): Path File: '/storage/emulated/0/Android/data/com.example.ecommerceapp/files/Pictures/068e58d6-88af-4b13-9453-c8c8d836083c5388058709499582194.jpg'

the exact error massage was:

The following assertion was thrown building UploadPage(dirty, dependencies: 
[MediaQuery, _InheritedTheme, _LocalizationsScope-[GlobalKey#71a32]], state: _UploadPageState#0a649):

'package:flutter/src/painting/image_provider.dart': Failed assertion: line 854 pos 14: 'file != 
null': is not true.

When checking the links that that error gave, it points to FileImage(imageFile). If I open up FileImage, line 854 pos 14 is an assertion:

const FileImage(this.file, { this.scale = 1.0 })
: assert(file != null),
  assert(scale != null);

I also tried the traditional way of creating an ImagePicker function. (the one in pub.dev) but it's still showing the same error. Any guidance will be much appreciated. Thank you!

4 Answers

it's because you are making a call of clearFormInfo() function inside IconButton widget. I believe that you wanted to call this function inside callback onPressed property.

So instead of:

leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
          onPressed: clearFormInfo(),
        )

Please use:

leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
          onPressed: () {
            clearFormInfo();
          },
        ),

You need to check if the imageFile is null. If it is, then you can use a simple Container until imageFile is not null. Try something like this:

Container(
    height: 230.0,
    width: MediaQuery.of(context).size.width * 0.8,
    child: Center(
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: imageFile != null // Here is important!
        ? Container(
           decoration: BoxDecoration(
            image: DecorationImage(
              image: FileImage(imageFile),
              fit: BoxFit.cover,
            ),
           ),
          )
        : Container(),
      ),
    ),
  ),

displayAdminUploadFormScreen() is a function and not a widget right?

So does this function can get the value of imageFile correctly?

Try to print the imageFile at the start of this function, to check if you get the image path correctly.

displayAdminUploadFormScreen(){
  print(imagePath);
  .
  // rest of code
  .
}

If the result is null, then then you might need to pass the imageFile

displayAdminUploadFormScreen(File imageFile){
  print(imagePath);
  .
  // rest of cocde
  .
}

and

@override
Widget build(BuildContext context) {
   return imageFile == null
    ? displayAdminHomeScreen()
    : displayAdminUploadFormScreen(imageFile);
}

Have you set the permissions inside Info.plist and AndroidManifest.xml files?

Inside **/path/to/project/android/app/src/[debug/main/profile] you need to put something like

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Inside **/path/to/project/ios/Runnmer/Info.plist you need to put something like

<key>NSCameraUsageDescription</key>
<string>camera</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photos for this</string>

I'm not 100% sure on the Android one as I haven't developed for Android yet, but i'm sure that's true of the iOS version.

Related