0

I have a page to allow a user to post something, which includes an image. When the page loads, it loads a default.png image and when the user clicks on it, the user is redirected to another page where they can take a picture or choose from a gallery.

The main issue here is that when my post an item page loads it looks at the Image.asset and see's null. Therefore, Image.asset is able to load the defaultImage, BUT when the user chooses an image or takes a picture the value that is returned is a File and with the path attached to it makes it into a String (as seen below)

child: Image.asset(
                    imageName1?.path ?? defaultImage,
                    fit: BoxFit.cover,
                  ),

So, Image.asset is not able to load this File.path

This is the error that I get:

Exception has occurred.
FlutterError (Unable to load asset: /data/user/0/com.flutter_project/cache/image_picker4920072427102948834.jpg)

I know that Image.file works with file.path... but do I really need to make an if statement somewhere to ensure proper image display?

Is there some simpler way?

Extra note: when I do a refresh in my visual studio (while my app is running) the image actually loads (as it should)... very weird... my page is stateful and when I pass the result (the file from the popped page) I do a setstate to imageName1

final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => PhotoPreviewPage()),
);

setState(() {
imageName1 = result;
});

1 Answer 1

1

You can do like this below.

File imageName1;

and once you got the image from the popped route with the selected image result from the navigator.

final result = await Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => PhotoPreviewPage()),
);

setState(() {
  imageName1 = File(result.path);
});

In the build method.

(imageName1 == null)
    ? ClipOval(
       child: SizedBox(
       width: 120.0,
       height: 120.0,
       child: CachedNetworkImage(
         imageUrl: (widget.user.userImg != null) ? widget.user.userImg ?? '' : AssetImages.course,
         placeholder: (context, url) => Center(child: CircularProgressIndicator()),
         errorWidget: (context, url, error) => Image.asset(AssetImages.smallLoader),
         fit: BoxFit.fill,
        ),
      ),
     )
     : ClipOval(
         child: Image.file(
           imageName1,
           width: 120,
           height: 120,
           fit: BoxFit.cover,
         ),
       ),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.