You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

引入dart:html编译Android应用报错,求跨端生命周期检测解决方案

解决Flutter跨端(Web/Android)应用生命周期检测的编译错误问题

问题原因

直接导入dart:html会导致Android编译失败,因为该库是Web平台专属依赖,移动端Flutter运行时无法识别其URI,从而抛出FileSystemException。

解决方案

1. 替换平台判断逻辑

使用Flutter官方提供的kIsWeb(来自package:flutter/foundation.dart)替代自定义的isWebApp(),平台判断更准确可靠。

2. 条件导入Web专属库

通过Dart的条件导入语法,仅在Web环境下加载dart:html,非Web环境用空存根文件占位,避免编译错误。

3. 修正核心代码

以下是调整后的完整可运行代码:

导入必要依赖

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
// 条件导入:Web环境加载dart:html,其他环境加载空存根文件
import 'dart:html' as html if (dart.library.io) 'stub_html.dart';

创建stub_html.dart文件(内容为空),用于非Web平台编译占位。

生命周期监听代码

@override
void onInit() {
  super.onInit();

  if (kIsWeb) {
    html.window.addEventListener('focus', onFocus);
    html.window.addEventListener('blur', onBlur);
  } else {
    WidgetsBinding.instance.addObserver(this);
  }
}

void onFocus(html.Event e) {
  didChangeAppLifecycleState(AppLifecycleState.resumed);
}

void onBlur(html.Event e) {
  didChangeAppLifecycleState(AppLifecycleState.paused);
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  super.didChangeAppLifecycleState(state);
  printWithDateTime("111111");
  if (state == AppLifecycleState.resumed) {
    getEmployee();
    homeDashboard();
  }
}

// 销毁时移除监听,防止内存泄漏
@override
void onClose() {
  if (kIsWeb) {
    html.window.removeEventListener('focus', onFocus);
    html.window.removeEventListener('blur', onBlur);
  } else {
    WidgetsBinding.instance.removeObserver(this);
  }
  super.onClose();
}

额外提示

  • 务必在控制器销毁时移除所有监听事件,避免内存泄漏。
  • Web端的focus/blur事件与移动端的resumed/paused生命周期状态映射逻辑正确,可直接沿用。

内容的提问来源于stack exchange,提问作者Honey Last

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:55:24