我有一个要求,我需要动态地创建一个webview,其中web资产以zip的形式在线存储。在加载我的移动的,我需要下载文件和解压,并加载在webview。为此,我写了代码。我能够下载,解压和获得文件访问,但无法加载它在UI。请查看我的代码,并帮助我哪里错了。此外,是否有可能加载的资产的Web动态或只有静态的方法,它可以?
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');
}
}
}
字符串
1条答案
按热度按时间qvsjd97n1#
如何尝试读取一个文件作为字符串和加载字符串通过
loadHtmlString
字符串
如果你正在使用JavaScript,也要确保你启用了JavaScript。