Last active
July 31, 2024 06:49
-
-
Save pmatatias/090eab8720333def84754ec4e20f785e to your computer and use it in GitHub Desktop.
preview iframe in flutter web
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ignore: avoid_web_libraries_in_flutter | |
| import 'dart:html' as html; | |
| import 'dart:ui_web' as ui; | |
| import 'package:flutter/material.dart'; | |
| class WebIframeHanlder extends StatefulWidget { | |
| final String source; | |
| const WebIframeHanlder({super.key, required this.source}); | |
| @override | |
| State<WebIframeHanlder> createState() => _WebIframeHanlderState(); | |
| } | |
| class _WebIframeHanlderState extends State<WebIframeHanlder> { | |
| final html.IFrameElement _iframeElement = html.IFrameElement(); | |
| @override | |
| void initState() { | |
| super.initState(); | |
| _iframeElement.src = widget.source; | |
| _iframeElement.style.border = 'none'; | |
| _iframeElement.style.width = '100%'; | |
| _iframeElement.style.height = '100%'; | |
| // ignore: undefined_prefixed_name | |
| ui.platformViewRegistry.registerViewFactory( | |
| widget.source, //use source as registered key to ensure uniqueness | |
| (int viewId) => _iframeElement, | |
| ); | |
| // Add the iframe to the UI | |
| html.document.body!.children.add(_iframeElement); | |
| } | |
| @override | |
| void dispose() { | |
| _iframeElement.remove(); | |
| super.dispose(); | |
| } | |
| @override | |
| Widget build(BuildContext context) { | |
| return Scaffold( | |
| appBar: AppBar( | |
| backgroundColor: Colors.indigo, | |
| title: const Text( | |
| "Web Iframe Handler", | |
| style: TextStyle(color: Colors.white), | |
| )), | |
| body: HtmlElementView( | |
| key: UniqueKey(), | |
| viewType: widget.source, | |
| ), | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment