Flutter Web renderer: doesn't show Image on the chrome browser but works on android.
Flutter可以跑在chrome瀏覽器上,但一執行卻出現無法顯示圖片的錯誤訊息.
這到底是怎麼了? 太奇怪了吧,花了半天檢查程式碼是否有寫錯.
Image.network(
"https://flutter.cn/assets/flutter-lockup-1caf6476beed76adec3c477586da54de6b552b2f42108ec5bc68dc63bae2df75.png"),
語法是對的,但跑在瀏覽器上就是會出現大叉叉.
When the exception was thrown, this was the stack:
Image provider: CachedNetworkImageProvider("https://via.placeholder.com/150/a46a91", scale: 1)
Image key: CachedNetworkImageProvider("https://via.placeholder.com/150/a46a91", scale: 1)
=====
Exception caught by image resource service ==
The following ImageCodecException was thrown resolving an image codec:
Failed to load network image.
Image URL: https://via.placeholder.com/150/323599
Trying to load an image from another domain?
----
然後我才發現,同樣的flutter code,但在android 平台上可以跑(右圖).
但放在電腦chrome 卻不能正常執行,顯示的圖片上出現驚嘆號(左圖).
原來不是程式寫錯.
原因似乎在這:
flutter web has upgraded default rendered(HTML) -> CanvasKit and it has better performance.
https://flutter.dev/docs/development/platform-integration/web-images
----
Flutter renderers on the web
Flutter offers a choice of two renderers on the web: (官方說明)
-
HTML: this renderer uses a combination of HTML,
CSS, Canvas 2D, and SVG to render UI.
It uses the
<img>
element to render images. - CanvasKit: this renderer uses WebGL to render UI, and therefore requires access to the pixels of the image.
--web-renderer
可選參數值為 auto
、html
或 canvaskit
。
auto
(默認)- 自動選擇渲染器。行動端上會自動選擇 HTML,桌面端瀏覽器會自動選擇 CanvasKit。 所以問題就出在這.
This flag can be used with the run
or build
subcommands.
For example:
flutter run -d chrome --web-renderer html
flutter build web --web-renderer canvaskit
所以要讓瀏覽器上的圖片能顯示,需要在terminal (android studio) 上執行下列指令.
flutter run -d chrome --web-renderer=html
需切換到html渲染才可以在 chrome上執行,因此不是你的程式碼有問題.
不過這樣子需要每次都要執行指令一次實在很麻煩,
有沒有設定一次以後就不用再設定的永久方法呢?
有的!
-----
Choose your Flutter web renderer
Run/ Run.../ Edit Configurations.../
, then in Additional arguments
add this
--web-renderer html
這樣就一勞永逸,不用每次都要設定一次.
留言
張貼留言