我正在尝试在本地 HTML 文件中嵌入图像。并尝试通过 flutter review 加载该 HTML 文件。网页文本正在显示,但没有显示本地引用的图像。
网页视图
class _HomeState extends State<Home> {
WebViewController _webViewController;
@override
Widget build(BuildContext context) {
return Container(
color: Colors.orange,
child: WebView(
initialUrl: "",
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (controller){
_webViewController = controller;
_loadHtmlFromAssets();
},
),
);
}
_loadHtmlFromAssets() async {
String fileHtmlContents = await rootBundle.loadString("assets/test.html");
_webViewController.loadUrl(Uri.dataFromString(fileHtmlContents,
mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
html
<h1>Hellop</h1>
<img src="myimage.jpg">
Run Code Online (Sandbox Code Playgroud)
您可以使用flutter_inappwebview该插件。首先定义你的资源目录pubspec.yaml
assets:
- assets/index.html
- assets/img/
Run Code Online (Sandbox Code Playgroud)
创建用于内容交付的本地服务器。
InAppLocalhostServer localhostServer = new InAppLocalhostServer();
Run Code Online (Sandbox Code Playgroud)
运行服务器
void main() async {
await localhostServer.start();
runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)
添加InAppWebView到您的小部件树中。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: InAppWebView(
initialUrl: "http://localhost:8080/assets/index.html",
initialOptions: InAppWebViewWidgetOptions(
inAppWebViewOptions: InAppWebViewOptions(
debuggingEnabled: true,
)
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
停止服务器
@override
void dispose() {
localhostServer.close();
super.dispose();
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个示例项目,您可以在这里找到https://github.com/zakir01913/flutter_webview_with_local_assest
| 归档时间: |
|
| 查看次数: |
2476 次 |
| 最近记录: |