0

I want to show some generated HTML in a WebView in my Flutter App. The StatefulWidget which contains the WebView can change certain properties upon which the WebView would have to rebuild.

TL;DR: How to supply custom HTML without initialUrl?

Up to now I used the initialUrl propety of the WebView constructor to supply an URI with my HTML directly embedded:

WebView(
  initialUrl: Uri.dataFromString(myHtml, mimeType: 'text/html').toString(),
)

Now I realized, I must rebuild the WebView with different values when some states get set. (Namely a dropdown above the WebView). As the name tells, this URI is just initial.

So my question is: How can I update the HTML in the WebView? Is there maybe some way to reset the internal state of the WebView?

1 Answer 1

1

I guess webview's api doesn't allow to do that, but you can use a workaround: just save the HTML to temp file and provide an URI to WebView using initialUrl. Here's the example:

import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter/webview_flutter.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Uri uri;

  Future<void> _showHtml(String html) async {
    final tempDir = await getTemporaryDirectory();
    final path = join(tempDir.path, 'page.html');
    final tempFile = File(path);
    tempFile.writeAsStringSync(html);
    setState(() {
      uri = Uri(scheme: 'file', path: path);
    });
  }

  @override
  void initState() {
    super.initState();
    _showHtml('<html>Test</html>');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: uri != null ? WebView(
          initialUrl: uri.toString(),
        ) : Container()
      ),
    );
  }
}

You can also use onWebViewCreated callback to save webview's controller and use the controller later to load other using loadUrl method.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.