I have a requirement that I need to create a webview dynamically where the web assets are stored online as a zip. On load of my mobile I need to download the file and unzip it and load it in the webview. For this, I have written the code. I am able to download, unzip and get the file access but, could not load it in the UI. Please look into my code and help me where I am wrong. Also, is it possible the load the assets of web dynamically or only with static approach it can be possible?
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');
}
}
}
2
Answers
how about try to read a file as string and load the string via
loadHtmlString
also make sure u enable javascript if you are using any.
I think you should be using the loadFile from the WebViewController from the webview_flutter package, not loadUrl
loading assets (I assume you mean css, images etc) does work, but they have to be given relative to the html file(s)
so if you have (after unzipping the files)
the css in index.html has to be referenced as