webview_flutter 3.0.4 - dark mode does not work

Viewed 78

I have a flutter app with a dark and light theme. The theme is selected according to the device theme or can be changed locally in the app. But in webview the background is always light and I don't know how to change the webview theme to dark. Do you have any tips on how to solve this?

2 Answers

A webview is basically shows a website inside a container. The theme that you are managing in the app is not connected to the website you load in WebView. To change the theme of the website you should probably edit the website directly.

So the solution that fixed my problem was injecting javascript as follows:

String js = "javascript: (function () { var css = 'html {-webkit-filter: invert(100%);' +    '-moz-filter: invert(100%);' +     '-o-filter: invert(100%);' +     '-ms-filter: invert(100%); }',head = document.getElementsByTagName('head')[0],style = document.createElement('style');style.type = 'text/css';if (style.styleSheet){style.styleSheet.cssText = css;} else {style.appendChild(document.createTextNode(css));}head.appendChild(style);}());";


controller.runJavascript(js);

This code does color inversion, of course you can inject css via javascript and make more sophisticated changes.

Related