Repository: flutter
Issue: [webview_flutter_android] crashes on NPE in onConsoleMessage
Labels: c: crash,platform-android,p: webview,package,P2,needs repro info,team-android,triaged-android

### Is there an existing issue for this?

- [X] I have searched the [existing package issues](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Apackage)
- [X] I have read the [guide to filing a bug](https://flutter.dev/docs/resources/bug-reports)

### What package does this bug report belong to?

webview_flutter

### What target platforms are you seeing this bug on?

Android

### Have you already upgraded your packages?

Yes

### Dependency versions

<details><summary>pubspec.lock</summary>

```lock
...
  webview_flutter:
    dependency: "direct main"
    description:
      name: webview_flutter
      sha256: c1ab9b81090705c6069197d9fdc1625e587b52b8d70cdde2339d177ad0dbb98e
      url: "https://pub.dev"
    source: hosted
    version: "4.4.1"
  webview_flutter_android:
    dependency: "direct main"
    description:
      name: webview_flutter_android
      sha256: b0cd33dd7d3dd8e5f664e11a19e17ba12c352647269921a3b568406b001f1dff
      url: "https://pub.dev"
    source: hosted
    version: "3.12.0"
  webview_flutter_platform_interface:
    dependency: "direct main"
    description:
      name: webview_flutter_platform_interface
      sha256: "6d9213c65f1060116757a7c473247c60f3f7f332cac33dc417c9e362a9a13e4f"
      url: "https://pub.dev"
    source: hosted
    version: "2.6.0"
  webview_flutter_wkwebview:
    dependency: "direct main"
    description:
      name: webview_flutter_wkwebview
      sha256: "30b9af6bdd457b44c08748b9190d23208b5165357cc2eb57914fee1366c42974"
      url: "https://pub.dev"
    source: hosted
    version: "3.9.1"
...
```

</details>


### Steps to reproduce

1. We have an app using a `WebViewWidget`. We use this to load a SPA web application which contains quite some console.logs.
2. Start a debug Android build of the app on a remotely connected Chromebook.
3. Wait for the web application to load.
4. Ensure some console.logs are fired in the web application.
5. Occasionally, we observe a crash with the following stack trace: 

```
W/System.err(15620): java.lang.NullPointerException
W/System.err(15620): 	at java.util.Objects.requireNonNull(Objects.java:220)
W/System.err(15620): 	at io.flutter.plugins.webviewflutter.WebChromeClientFlutterApiImpl.onConsoleMessage(WebChromeClientFlutterApiImpl.java:180)
W/System.err(15620): 	at io.flutter.plugins.webviewflutter.WebChromeClientHostApiImpl$WebChromeClientImpl.onConsoleMessage(WebChromeClientHostApiImpl.java:114)
W/System.err(15620): 	at WV.xc.addMessageToConsole(chromium-TrichromeWebViewGoogle.aab-stable-593815331:97)
W/System.err(15620): 	at android.os.MessageQueue.nativePollOnce(Native Method)
W/System.err(15620): 	at android.os.MessageQueue.next(MessageQueue.java:335)
W/System.err(15620): 	at android.os.Looper.loop(Looper.java:183)
W/System.err(15620): 	at android.app.ActivityThread.main(ActivityThread.java:7741)
W/System.err(15620): 	at java.lang.reflect.Method.invoke(Native Method)
W/System.err(15620): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
W/System.err(15620): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:966)
```

We are not yet sure _when_ it exactly happens.

### Expected results

No crashes.

### Actual results

The application exits.

### Code sample

<details><summary>Code sample</summary>

```dart
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _webviewController = WebViewController();

  @override
  void initState() {
    super.initState();

    _initController();
  }

  Future<void> _initController() async {
    if (WebViewPlatform.instance is AndroidWebViewPlatform) {
      await _webviewController.setJavaScriptMode(JavaScriptMode.unrestricted);
    }
    
    _webviewController.loadRequest(Uri.parse('https://jsfiddle.net/5pL2nysd/'));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              width: 400,
              height: 400,
              child: WebViewWidget(
                controller: _webviewController,
              ),
            )
          ],
        ),
      ),
    );
  }
}
```

</details>


### Screenshots or Videos

<details>
<summary>Screenshots / Video demonstration</summary>

[Upload media here]

</details>


### Logs

<details><summary>Logs</summary>

```console
...
I/chromium(29132): [INFO:CONSOLE(84509)] "[object Object]", source: http://<redacted>.js (84509)
W/Choreographer(29132): Frame time is 0.049597 ms in the future!  Check that graphics HAL is generating vsync timestamps using the correct timebase.
W/System.err(29132): java.lang.NullPointerException
W/System.err(29132): 	at java.util.Objects.requireNonNull(Objects.java:220)
W/System.err(29132): 	at io.flutter.plugins.webviewflutter.WebChromeClientFlutterApiImpl.onConsoleMessage(WebChromeClientFlutterApiImpl.java:180)
W/System.err(29132): 	at io.flutter.plugins.webviewflutter.WebChromeClientHostApiImpl$WebChromeClientImpl.onConsoleMessage(WebChromeClientHostApiImpl.java:114)
W/System.err(29132): 	at WV.xc.addMessageToConsole(chromium-TrichromeWebViewGoogle.aab-stable-593815331:97)
W/System.err(29132): 	at android.os.MessageQueue.nativePollOnce(Native Method)
W/System.err(29132): 	at android.os.MessageQueue.next(MessageQueue.java:335)
W/System.err(29132): 	at android.os.Looper.loop(Looper.java:183)
W/System.err(29132): 	at android.app.ActivityThread.main(ActivityThread.java:7741)
W/System.err(29132): 	at java.lang.reflect.Method.invoke(Native Method)
W/System.err(29132): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
W/System.err(29132): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:966)
```

</details>


### Flutter Doctor output

<details><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.13.1, on macOS 13.6 22G120 darwin-x64, locale en-NL)
    • Flutter version 3.13.1 on channel stable at /Users/<redacted>/fvm/versions/3.13.1
    • Upstream repository git@github.com:/flutter/flutter.git
    • FLUTTER_GIT_URL = git@github.com:/flutter/flutter.git
    • Framework revision e1e47221e8 (8 weeks ago), 2023-08-22 21:43:18 -0700
    • Engine revision b20183e040
    • Dart version 3.1.0
    • DevTools version 2.25.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.2)
    • Android SDK at /Users/<redacted>/Library/Android/sdk
    • Platform android-33, build-tools 33.0.2
    • ANDROID_HOME = /Users/<redacted>/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15A240d
    • CocoaPods version 1.12.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301)

[✓] VS Code (version 1.83.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.74.0

[✓] Connected device (3 available)
    • corsola (mobile) • 10.50.2.213:5555 • android-arm64  • Android 11 (API 30)
    • macOS (desktop)  • macos            • darwin-x64     • macOS 13.6 22G120 darwin-x64
    • Chrome (web)     • chrome           • web-javascript • Google Chrome 118.0.5993.88
    ! Error: Browsing on the local area network for iPad. Ensure the device is unlocked and attached with a cable or associated with the same local area network as this Mac.
      The device must be opted into Developer Mode to connect wirelessly. (code -27)

[✓] Network resources
    • All expected network resources are available.

• No issues found!
```

</details>