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

Flutter Web:如何在新窗口打开硬编码的HTML内容?

在Flutter Web新窗口打开硬编码HTML内容的正确方法

你用Uri.dataFromString的方式打开HTML出现空白,是因为浏览器对data URI的渲染存在安全限制,确实需要通过Blob来实现,具体步骤如下:

  1. 将硬编码的HTML字符串转为Blob对象,指定正确的MIME类型
  2. 生成Blob对应的临时URL
  3. 用url_launcher打开这个临时URL,用完后释放资源避免内存泄漏

完整代码示例:

import 'dart:html' as html;
import 'package:url_launcher/url_launcher.dart';

Future<void> launchCustomHtml() async {
  final htmlContent = '<html><body><h1>Hello World</h1><p>This is custom HTML content</p></body></html>';
  
  // 创建Blob对象
  final blob = html.Blob([htmlContent], 'text/html');
  // 生成Blob的临时URL
  final blobUrl = html.Url.createObjectUrlFromBlob(blob);
  
  try {
    // 打开新窗口
    await launchUrl(
      Uri.parse(blobUrl),
      mode: LaunchMode.externalApplication,
    );
  } catch (e) {
    print('打开失败: $e');
  } finally {
    // 释放Blob URL,避免内存泄漏
    html.Url.revokeObjectUrl(blobUrl);
  }
}

注意事项:

  • dart:html仅在Web环境可用,跨平台项目需通过条件导入或平台判断执行这段代码
  • 确保url_launcher已正确添加到项目依赖中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:54:55