Flutter WebView键盘输入与JS-Flutter通信问题及解决方案
Hey there, let's walk through solutions for your two WebView pain points in Flutter—getting keyboard input working with webview_flutter, and setting up JavaScript-Flutter communication with flutter_webview_plugin:
webview_flutter If your input fields in webview_flutter aren’t triggering the keyboard, try these targeted fixes:
First, adjust your WebView configuration to handle focus and JavaScript properly. Here’s an updated snippet tailored to your local HTML use case:
WebView( initialUrl: Uri.dataFromString(data, mimeType: 'text/html').toString(), javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (WebViewController controller) { // Explicitly request focus for the WebView to enable keyboard input controller.focus(); }, // Use EagerGestureRecognizer to ensure touch events reach input elements gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ Factory<OneSequenceGestureRecognizer>( () => EagerGestureRecognizer(), ), }, )
For Android, tweak the soft keyboard behavior in AndroidManifest.xml to prevent the WebView from being obscured:
<activity android:name=".MainActivity" android:windowSoftInputMode="adjustResize"> </activity>
Double-check your HTML too—ensure input elements don’t have readonly attributes or CSS like pointer-events: none that would block user input.
flutter_webview_plugin The official flutter_webview_plugin has gaps in JS-Flutter communication, but the forked version you referenced fixes these issues (along with keyboard input). Here’s how to implement it:
First, add the forked dependency to your pubspec.yaml:
dependencies: flutter_webview_plugin: git: url: https://github.com/rinlv/flutter_webview_plugin.git
Sending Messages from Flutter to JavaScript
Use evalJavascript to run JavaScript code directly from Dart:
final flutterWebviewPlugin = FlutterWebviewPlugin(); // Call a JavaScript function or execute custom code flutterWebviewPlugin.evalJavascript('showAlert("Hello from Flutter!")');
Receiving Messages from JavaScript in Flutter
In your HTML/JavaScript, send messages using window.postMessage:
// Send a message to Flutter window.postMessage('User interacted with the WebView', '*');
Then listen for these messages in your Flutter code:
final flutterWebviewPlugin = FlutterWebviewPlugin(); flutterWebviewPlugin.onMessage.listen((String message) { print('Received from JS: $message'); // Add your custom logic to handle the message here });
This forked plugin resolves both the keyboard input and JS communication issues you were facing, making it a solid all-in-one solution.
内容的提问来源于stack exchange,提问作者Samy Smart

