Home > Software design >  Loading image in Flutter | Path from content root doesn't work, but absolute path works
Loading image in Flutter | Path from content root doesn't work, but absolute path works

Time:07-02

Very simple app, the image is in project/images folder.

  1. When I try to load it from the relative path: 'images/diamond.png'

the image doesn't load.

  1. When I do it from the absolute path: '/Users/MacBookAir/StudioProjects/secondtry_iamrich/images/diamond.png'

it does.

Why is this? Can anyone please help?

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.blueGrey,
        appBar: AppBar(
          title: const Text('I am Rich'),
          backgroundColor: Colors.blueGrey[900],
        ),
        body: const Center(
          child: Image(
            image: AssetImage('images/diamond.png'),
          ),
        ),
      ),
    ),
  );
} 

This is the error it is providing:

======= Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: images/diamond.png

When the exception was thrown, this was the stack: 
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:237:7)
<asynchronous suspension>
#1      AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:658:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "images/diamond.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#99cb5(), name: "images/diamond.png", scale: 1.0)
====================================================================================================

CodePudding user response:

Uncomment and change the asset section in your pubspect.yaml file can fix it.

  assets:
    - images/

CodePudding user response:

Do not forgot to add image folder path to your pubspec.ymal folder like

  assets:
    - assets/images/
    - assets/images/icons/
    - assets/loader.json

enter image description here

Use this plugin in your android studio it will auto generate your all assets no need to write path.

Use it like this

Image.asset(Assets.imagesNoDataFound, scale: 3.5)
  • Related