【发布时间】:2020-10-13 04:27:26
【问题描述】:
我有一个 zip 文件要下载。下载后,我将其保存在外部存储(/storage/emulated/0/Android/data/...)中。我想从存储中显示一个 html 页面。
如何使用 webview 显示 html 页面? 我还想要一个可以在我单击 webview 中的某些内容时加载的 javascript 函数。
我尝试过使用inappwebview,但它无法从外部存储加载本地 html 文件。
【问题讨论】:
我有一个 zip 文件要下载。下载后,我将其保存在外部存储(/storage/emulated/0/Android/data/...)中。我想从存储中显示一个 html 页面。
如何使用 webview 显示 html 页面? 我还想要一个可以在我单击 webview 中的某些内容时加载的 javascript 函数。
我尝试过使用inappwebview,但它无法从外部存储加载本地 html 文件。
【问题讨论】:
使用flutter_inappwebview插件(使用资产,你可以操纵使用任何你想要的)
dependencies:
flutter:
sdk: flutter
flutter_inappwebview:
assets:
- assets/index.html
- assets/css/
- assets/images/
- assets/js/
- assets/conditions/
您要做的基本上是在应用程序内创建一个本地服务器,并在 WebView 中运行 HTML 应用程序。
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
InAppLocalhostServer localhostServer = new InAppLocalhostServer();
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await localhostServer.start();
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Hi! There!!',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State < MyHomePage > {
InAppWebViewController webView;
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
if (await webView.canGoBack()) {
webView.goBack();
return false;
}
return true;
},
child: Scaffold(
body: Container(
child: Column(children: < Widget > [
Expanded(
child: Container(
margin: const EdgeInsets.only(top: 30.0),
child: InAppWebView(
initialUrl: "http://localhost:8080/assets/index.html",
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
),
),
)
])
),
),
);
}
@override
void dispose() {
localhostServer.close();
super.dispose();
}
}
【讨论】: