问题
I have a zip file to download. After it has been downloaded, I save it in External Storage (/storage/emulated/0/Android/data/...). I want to show a html page from the storage.
How to show the html page using webview? I also want a javascript function that can be loaded when I clicked something in webview.
I've tried using inappwebview but it can't load local html file from external storage.
回答1:
using flutter_inappwebview plugin (using assets ,you can manpulate to use whatever you want)
dependencies:
flutter:
sdk: flutter
flutter_inappwebview:
assets:
- assets/index.html
- assets/css/
- assets/images/
- assets/js/
- assets/conditions/
What you will do basically is you’ll create a local server inside the app and it’ll run the HTML app there in the WebView.
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();
}
}
来源:https://stackoverflow.com/questions/62529184/how-to-show-a-local-html-in-flutter