Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to load assets images due to whitespace in image name

Tags:

flutter

Hey I have many images in my assets folder and I use the following code to get the list of images

...

List<String> imagesList;

 Future _initImages() async {
    final manifestContent =
        await DefaultAssetBundle.of(context).loadString('AssetManifest.json');

    final Map<String, dynamic> manifestMap = json.decode(manifestContent);


    final imagePaths = manifestMap.keys
        .where((String key) => key.contains('images/')) // mention folder where all images exists
        .toList();

    print('imagePath ${imagePaths.length}');

    setState(() {
      imagesList = imagePaths;
    });
  }

  void initState() {
    // TODO: implement initState
    super.initState();
    _initImages();
  }

...

So the issue is that my images name contains whitespace and while print I imagePaths, I get path something like this

' my%20image%20.jpg ' 

which means I think it is unable to count whitespace and when I give this path to Image it gives unable to load assets error. Any solution?

path of one of the image :

assets/images/my image.jpg
like image 242
Sachin Avatar asked Oct 22 '25 19:10

Sachin


2 Answers

Here the problem is the spaces. If the path is:

"assets/images/my image.jpg"

Due to spaces you are getting the path as

"assets/images/my%20image.jpg"

In flutter giving path to Image.asset as

Image.asset("assets/images/my image.jpg"),

will render the image.

but Image.asset("assets/images/my%20image.jpg"), will throw error.

Hence, before appending all paths to your list, make sure you remove all %20 and then append the path to the list.

For that, you can use https://api.dart.dev/stable/2.8.4/dart-core/String/replaceAll.html

Example:

String path = "assets/images/my%20myimage%20spacex%20launchAmerica.png";
String newpath = path.replaceAll("%20", " ");
print("NewValidPath is : $newpath");

Output:

NewValidPath is : assets/images/my myimage spacex launchAmerica.png

Now, this is a valid path. Hence this will render the image.

Edit: As per your situation you can do the following:

var pathList = manifestMap.keys.toList();
 for(int i=0;i<pathList.length;i++){
      pathList[i]=pathList[i].replaceAll("%20", " ");
 }
 setState((){
    imagesList=pathList;
 });

I hope this helps!

like image 190
ANUP SAJJAN Avatar answered Oct 25 '25 10:10

ANUP SAJJAN


EDIT: From my understanding you want to remove %20 and replace with a space.

After researching, i have found a better solution

String imagePath = "my%20image";

String newPath = Uri.decodeFull(imagePath);
print(newPath) //Prints my image

Try it out.

like image 28
Julitech Avatar answered Oct 25 '25 10:10

Julitech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!