mehdouch
mehdouch

Reputation: 453

local flutter asset image not showing in html widget

I am using flutter_html to render html code and it is working well but I am having a problem with img tag

The img tag work well when the image is from the web like this:

<img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">

but it doesn't work when it's a local asset image file Note: I can use the same image in an Image widget like this:

Image.asset('assets/images/logo_tst.png'),

but it wont show in html code and I tried all these:

String htmlUrl = '''  
<img src="file:///storage/assets/images/logo_tst.png" alt="web-img1" >
<img src="file:///assets/images/logo_tst.png" alt="web-img2">
<img src="file:///images/logo_tst.png" alt="web-img3">
''';

then I call it:

Html( data:htmlUrl),

And it only shows the alt:

web-img1
web-img2
web-img3

I am testing on an Android emulator and a device

what Am I doing wrong?

Thank you

Upvotes: 4

Views: 6057

Answers (3)

hatted
hatted

Reputation: 1597

Seems like the webview_flutter cannot read local CSS or local images(jpg/png file) by now. I have to change it to inline CSS and based64 images and it works perfectly.

Inline CSS:

<head>
<style>
body {
  background-color: linen;
}

h1 {
  color: maroon;
  margin-left: 40px;
}
</style>
</head>

Inline base64 images:

<img src="data:image/jpeg;base64,/9j/4RiDRXhpZgAATU0AKgA...">

To convert an image to base64 image in Mac, you can run the following command in Terminal.

openssl enc -base64 -in image.png -out image.b64

Upvotes: 1

mehdouch
mehdouch

Reputation: 453

I did it! I have found a solution and it wasn't obvious and not documented anywhere!

after searching for days the right way to use assets with the img tag I have decided to take a look at the source code of flutter_html in github and I have found these two lines:

else if (node.attributes['src'].startsWith('asset:')) {
                  final assetPath = node.attributes['src'].replaceFirst('asset:', '');

so I tried the img tag like this:

<img src="asset:assets/images/logo_tst.png" alt="web-img2">

By the way my image file is declared in pubspec.yaml as

assets/images/logo_tst.png

And It worked !!!

As I said there is no documentation about this and I hope that someone will add it

Upvotes: 8

Code Poet
Code Poet

Reputation: 8013

Try:

"file:///android_asset/flutter_assets/" + url

in other words:

"file:///android_asset/flutter_assets/assets/images/logo_tst.png"

Upvotes: 1

Related Questions