You need to enable JavaScript to run this app. Flutter Web更新后iFrame未在渲染框正确居中,不想降级如何修复
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web更新后iFrame未在渲染框正确居中,不想降级如何修复

Flutter版本迭代后Web端iFrame组件居中异常问题

项目一个月前可完全正常运行,经过数次Flutter版本更新后,iFrame组件在目标渲染容器中出现未正确居中的问题。

  • 效果对照:第一组为异常表现效果,第二组为此前正常版本的效果
  • 依赖说明:项目引入universal_ui插件,用于规避使用platformViewRegistry时的分析器报错
  • 修复约束:不打算通过降级旧版Flutter的方式解决问题
  • 已尝试方案:直接嵌套Center()组件无任何效果

效果对照截图:
异常表现效果
此前正常版本效果

项目中iFrame组件的实现代码:

// ignore: avoid_web_libraries_in_flutter
import 'dart:html';
// ignore: undefined_prefixed_name
import 'package:universal_ui/universal_ui.dart';

import 'package:flutter/material.dart';

class Iframe extends StatefulWidget {
  final String source;
  final Size size;
  Iframe(this.source, {this.size});
  @override
  _IframeState createState() => _IframeState();
}

class _IframeState extends State<Iframe> {
  Widget _iframeWidget;
  String source;
  @override
  void initState() {
    newFrame();
    super.initState();
  }

  void newFrame() async {
    print(widget.size);
    final String id = widget.source.hashCode.toString();
    final IFrameElement _iframeElement = IFrameElement();
    _iframeElement.height = widget.size?.height?.toString() ?? '500';
    _iframeElement.width = widget.size?.width?.toString() ?? '500';
    source = widget.source;
    _iframeElement.src = widget.source;
    _iframeElement.style.border = 'none';

    ui.platformViewRegistry
        .registerViewFactory(id, (int viewID) => _iframeElement);
    _iframeWidget = HtmlElementView(
      key: UniqueKey(),
      viewType: id,
    );
  }

  @override
  Widget build(BuildContext context) {
    if (source != widget.source) newFrame();
    return _iframeWidget;
  }
}

iFrame组件的实际使用示例:

class ChatClientAnon extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamCacheBuilder<Package>(
      stream: Database().streamPackage(),
      builder: (data) => Container(
        child: Row(
          children: [
            Expanded(child: SmartphoneClient('Anonym', isAnon: true), flex: 2),
            Expanded(
                child: LayoutBuilder(
                    builder: (_, c) =>
                        Iframe(data.source, size: c.biggest)),
                flex: 8),
          ],
        ),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 16:06:09