I have an .html file in my assets directory.
How can I display / render it in Flutter?
I have an .html file in my assets directory.
How can I display / render it in Flutter?
The package from the Flutter Team was released yesterday:
How to load local asset:
Add the file to the project and update your pubspec:
//...
assets:
//...
- assets/yourFile.html
//...
In your widget:
child: FutureBuilder<String>(
future: LocalLoader().loadLocal(),
builder: (context, snapshot) {
if (snapshot.hasData) {
// return Text("${snapshot.data}");
return WebView(
initialUrl: new Uri.dataFromString(snapshot.data,
mimeType: 'text/html')
.toString(),
// maybe you Uri.dataFromString(snapshot.data, mimeType: 'text/html', encoding: Encoding.getByName("UTF-8")).toString()
javascriptMode: JavascriptMode.unrestricted,
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
Loading the text from the file:
class LocalLoader {
Future<String> loadLocal() async {
return await rootBundle.loadString('assets/yourFile.html');
}
}
Unzip the apk package. I found the reason: path is wrong
For Android:
"assets/test.html" == "file:///android_asset/flutter_assets/assets/test.html"
so, just like this:
WebView(
initialUrl: "file:///android_asset/flutter_assets/assets/test.html",
javascriptMode: JavascriptMode.unrestricted,
)
you can load assets/test.html.
You can try my flutter_inappbrowser plugin (EDIT: it has been renamed to flutter_inappwebview), that is a Flutter Plugin that allows you to add an inline webview integrated with the widget tree or open an in-app browser window!
You can use the InAppWebView widget class or the InAppBrowser class and use its webview controller.
In your case, you can use the InAppWebViewController.loadFile method.
To be able to load your local files (html, js, css, etc.), you need to add them in the assets section of the pubspec.yaml file, otherwise they cannot be found!
Example of a pubspec.yaml file:
...
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
assets:
- assets/index.html
- assets/css/
- assets/images/
...
Then, call the method in your business logic:
inAppWebViewController.loadFile("assets/index.html");
or
InAppWebView(
onWebViewCreated: (InAppWebViewController controller) {
var uri = "assets/index.html"
controller.loadFile(assetFilePath: uri);
},
),
If you just need to render simple HTML tags (p,img,a,h1,etc.) you could try this flutter_html plugin
It's not mature enough for production yet IMHO but worth considering / contributing.