How to access local CSS, JS and Images from Flutter WebView

Viewed 3259

I am trying to embed an image within a local HTML file. and trying to load that HTML file through a flutter review. the web page texts are showing but no locally referred images are showing.

WebView

class _HomeState extends State<Home> {
  WebViewController _webViewController;
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.orange,
      child: WebView(
        initialUrl: "",
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller){
          _webViewController = controller;
          _loadHtmlFromAssets();
        },
      ),

    );
  }

  _loadHtmlFromAssets() async {
    String fileHtmlContents = await rootBundle.loadString("assets/test.html");
    _webViewController.loadUrl(Uri.dataFromString(fileHtmlContents,
            mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString());
  }
}

Html

<h1>Hellop</h1>
<img src="myimage.jpg">
1 Answers

You can use the flutter_inappwebview plugin for that. First define the asset directory in your pubspec.yaml

  assets:
    - assets/index.html
    - assets/img/

Create an local server for content delivery.

InAppLocalhostServer localhostServer = new InAppLocalhostServer();

Run the server

void main() async {
  await localhostServer.start();
  runApp(MyApp());
}

Add InAppWebView in your widget tree.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: InAppWebView(
        initialUrl: "http://localhost:8080/assets/index.html",
        initialOptions: InAppWebViewWidgetOptions(
            inAppWebViewOptions: InAppWebViewOptions(
              debuggingEnabled: true,
            )
        ),
      ),
    );
  }

Stop the server

  @override
  void dispose() {
    localhostServer.close();
    super.dispose();
  }

I have created a sample project which you can find here https://github.com/zakir01913/flutter_webview_with_local_assest

Related