简体   繁体   中英

How to get property AssetName from Image.asset in Flutter?

From an AssetImage object i'm trying to get the file name in Flutter.

 Image photo = Image.asset('assets/images/image-not-found.jpg');
 print(photo.image);           // AssetImage(bundle: null, name: "assets/images/image-not-found.jpg")
 print(photo.image.assetName);  // assetName not defined
 print(photo.image.name);       // name not defined

How to get this assetName property?

Something nicer without doing some regex on photo.image.toString() ;

EDIT:

the purpose here was to retrieve the image name in order to compare it. So i just go for direct comparaison.

if(photo.image == AssetImage('assets/images/image-not-found.jpg')){
  print("image was not found");
}

Try AssetImage for this.

var photo = AssetImage('assets/images/image-not-found.jpg');
print(photo.assetName);

//You can use split method like

`String toSplit = 'assets/images/image-not-found.jpg';

var imageName = toSplit.split("/");

print(var[2]);`

//You can get your image name stored in var[2].

First, add an asset folder in pubspec file like:

assets:
   - specify a folder where is your assets are stored.

and use like this

Image.asset(
    'assets/images/profile.png',
    fit: BoxFit.fill,
),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM