新版 Flutter Web使用 canvaskit 渲染組件.
會加載 canvaskit.js 和 canvaskit.wasm 這兩個文件
在國內加載這兩個文件很慢..
可以將這兩個文件放到自己的服務器,或其它高速服務器.
在編譯的時候使用 --dart-define=FLUTTER_WEB_CANVASKIT_URL="http://****/" 指定自定義下載地址。
解決方法
Canvaskit
是一個 js
框架,Flutter
定義默認是從 https://unpkg.com 去加載的,在國內最好是改變這個地址,讓它通過鏡像地址去加載.
編譯發布修改
在 {SDK_PATH}/bin/cache/flutter_web_sdk/lib/_engine/engine/canvaskit/initialization.dart
文件中有定義:
/// The URL to use when downloading the CanvasKit script and associated wasm. /// /// The expected directory structure nested under this URL is as follows: /// /// /canvaskit.js - the release build of CanvasKit JS API bindings /// /canvaskit.wasm - the release build of CanvasKit WASM module /// /profiling/canvaskit.js - the profile build of CanvasKit JS API bindings /// /profiling/canvaskit.wasm - the profile build of CanvasKit WASM module /// /// The base URL can be overridden using the `FLUTTER_WEB_CANVASKIT_URL` /// environment variable, which can be set in the Flutter tool using the /// `--dart-define` option. The value must end with a `/`. /// /// Example: /// /// ``` /// flutter run \ /// -d chrome \ /// --web-renderer=canvaskit \ /// --dart-define=FLUTTER_WEB_CANVASKIT_URL=https://example.com/custom-canvaskit-build/ /// ``` /// /// When CanvasKit pushes a new release to NPM, update this URL to reflect the /// most recent version. For example, if CanvasKit releases version 0.34.0 to /// NPM, update this URL to `https://unpkg.com/canvaskit-wasm@0.34.0/bin/`. const String canvasKitBaseUrl = String.fromEnvironment( 'FLUTTER_WEB_CANVASKIT_URL', defaultValue: 'https://unpkg.com/canvaskit-wasm@0.24.0/bin/', );
意思是可以通過 FLUTTER_WEB_CANVASKIT_URL 這個環境變量改變默認的下載地址.
所以我們只要在 flutter 命令后面加上 --dart-define=FLUTTER_WEB_CANVASKIT_URL=https://cdn.jsdelivr.net/npm/canvaskit-wasm@0.24.0/bin/ 就可以了
flutter run -d chrome --dart-define=FLUTTER_WEB_CANVASKIT_URL=https://cdn.jsdelivr.net/npm/canvaskit-wasm@0.24.0/bin/ --release