我有一个要求,我需要动态创建一个 Web 视图,其中 Web 资源以 zip 形式在线存储。在加载我的手机时,我需要下载文件并解压缩并将其加载到网络视图中。为此,我编写了代码。我可以下载、解压缩并获取文件访问权限,但无法在 UI 中加载它。请查看我的代码并帮助我哪里错了。另外,是否可以动态加载网络资源,或者仅使用静态方法?
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:archive/archive.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
class MyWebViewUsingInAppWebview extends StatelessWidget {
@OverRide
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Webview Example'),
),
body: InAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse('about:blank')),
onWebViewCreated: (InAppWebViewController webViewController) async {
await downloadAndUnzipFile(webViewController);
},
),
);
}
Future downloadAndUnzipFile(
InAppWebViewController webViewController) async {
String zipFilePath =
'files/forms-td-practice.zip'; // Replace with your zip file path
try {
firebase_storage.Reference ref =
firebase_storage.FirebaseStorage.instance.ref(zipFilePath);
String downloadURL = await ref.getDownloadURL();
Directory appDocDir = await getApplicationDocumentsDirectory();
File localFile = File('${appDocDir.path}/example.zip');
// Download the zip file to the local file system
await ref.writeToFile(localFile);
print('Zip file downloaded successfully! Saved to: ${localFile.path}');
// Unzip the file
String unzipPath =
appDocDir.path; // Unzip to the app's documents directory
List<int> bytes = localFile.readAsBytesSync();
Archive archive = ZipDecoder().decodeBytes(bytes);
for (ArchiveFile file in archive) {
String fileName = '${unzipPath}/${file.name}';
if (file.isFile) {
File outFile = File(fileName);
outFile.createSync(recursive: true);
outFile.writeAsBytesSync(file.content);
// If the current file is "index.html", load it into the WebView
if (file.name == 'forms-td-practice/forms-td-practice/index.html') {
webViewController.loadUrl(
urlRequest:
URLRequest(url: Uri.parse('file://${outFile.path}')));
}
}
}
print('Zip file extracted successfully!');
} catch (e) {
print('Error downloading/unzipping file: $e');
}
}
}
尝试将文件读取为字符串并通过
loadHtmlString
加载字符串如何
var htmlString="YOUR_HTML_STRING"
webViewController.loadHtmlString(htmlString);
如果您使用任何 JavaScript,请确保启用 JavaScript。
我认为你应该使用 webview_flutter 包中 WebViewController 的 loadFile,而不是 loadUrl
加载资源(我假设你的意思是CSS、图像等)确实有效,但它们必须相对于html文件给出 所以如果你有(解压缩文件后)
/css
mycss.css
index.html
index.html 中的 css 必须引用为
<link rel="stylesheet" media="all" type="text/css" href="../css/mycss.css">