1

I am displaying couple of images on first page using Image.asset . Idea is, when I click on one image, I should be able get the image name, so that I can send to next page and display the image with its detail. I am getting image in AssetImage format like

AssetImage(bundle: null, name: "images/image1.png")

How can I just extract the name?

4 Answers 4

3

You have to store image names in a list. And on tap image, you can access the image name from the list using index. Its the easiest solution to me.

Or in case you want to extract the name from assetImagePath, than... You can use RegEx, No extra package required :)

  String path = 'images/image1.png';
  RegExp exp = RegExp('\/((?:.(?!\/))+\$)');
  String fileName = exp.firstMatch(path).group(1);
  print(fileName); // image1.png

Test the Code here: https://dartpad.dev/

Sign up to request clarification or add additional context in comments.

Comments

2

you can achieve it by assigning the image name on a string

String img1 = "image1";

and use String concatenation operator to produces the image path

Image.asset('images/$img1.png')

and then you can pass the image name to a constructor.

Comments

1

First You have to make a clickable AssetImage using below code:

Material(
  child: GestureDetector(
    onTap: () {
    var imgName = "images/image1.png"
      **<< Pass image name as per your requirement >>**
     },
    child: Container(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(20.0),
        child: Image.asset('images/image1.png',
            width: 110.0, height: 110.0),
      ),
    ),
  ),
) 

Comments

0

You can use path library's function, called basename (see docs here)

For example:

File fileLocation = new File("/dir1/dir2/image.png"); // Here's the location of the image
String imageName = basename(fileLocation.path);
print(imageName); // The output should be => image.png

Don't forget to import the packages:

import 'package:path/path.dart';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.