flutter web网站 第一次访问首屏页 空白卡顿 再显示

新版 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

idea as run可以添加额外参数

posted @ 2021-08-12 15:14  安徽胡峻  阅读(2279)  评论(0编辑  收藏  举报