Repository: flutter
Issue: WebView sometimes isn't loaded when run with `IntegrationTestWidgetsFlutterBinding`
Labels: platform-android,p: webview,package,f: integration_test,has reproducible steps,P2,found in release: 3.10,team-android,triaged-android,found in release: 3.13

### Is there an existing issue for this?

- [X] I have searched the [existing issues](https://github.com/flutter/flutter/issues)
- [X] I have read the [guide to filing a bug](https://flutter.dev/docs/resources/bug-reports)

### Steps to reproduce

1. Create an empty project and `cd` into it

    ```
    flutter create example --platforms android --empty
    ```

1. Add dependency on `flutter_webview` and `integration_test`:

    ```yaml
    dependencies:
      webview_flutter: ^4.2.2

    # ...

    dev_dependencies:
      flutter_test:
        sdk: flutter
      integration_test:
        sdk: flutter
    ```

1. Modify `lib/main.dart` to show a button that, when tapped, opens [hackernews.com](hackernews.com) in a WebView:


    <details><summary>App code</summary>
    
    ```dart
    import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';
    
    void main() {
      runApp(const ExampleApp());
    }
    
    class ExampleApp extends StatelessWidget {
      const ExampleApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          darkTheme: ThemeData(
            primarySwatch: Colors.blue,
            brightness: Brightness.dark,
          ),
          theme: ThemeData(
            primarySwatch: Colors.blue,
            brightness: Brightness.light,
          ),
          home: const ExampleHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class ExampleHomePage extends StatelessWidget {
      const ExampleHomePage({super.key, required this.title});
    
      final String title;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text(title)),
          body: Center(
            child: TextButton(
              onPressed: () async => Navigator.of(context).push(
                MaterialPageRoute<void>(
                  builder: (_) => const WebViewScreen(
                    title: 'WebView (Hacker News)',
                    url: 'https://news.ycombinator.com',
                  ),
                ),
              ),
              child: const Text('Open webview (Hacker News)'),
            ),
          ),
        );
      }
    }
    
    class WebViewScreen extends StatefulWidget {
      const WebViewScreen({super.key, required this.title, required this.url});
    
      final String title;
      final String url;
    
      @override
      State<WebViewScreen> createState() => _WebViewScreenState();
    }
    
    class _WebViewScreenState extends State<WebViewScreen> {
      late final WebViewController controller;
    
      @override
      void initState() {
        super.initState();
        controller = WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onProgress: (progress) => print('WebView progress: $progress'),
              onPageStarted: (url) => print('WebView started loading: $url'),
              onPageFinished: (url) => print('WebView finished loading: $url'),
              onWebResourceError: (error) => print('WebView error: $error'),
            ),
          )
          ..loadRequest(Uri.parse(widget.url));
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text(widget.title)),
          body: WebViewWidget(controller: controller),
        );
      }
    }
    ```
    
    </details> 

1. Create a new test: `integration_test/webview_hackernews_test.dart`

    <details><summary>Test code</summary>
    
    ```dart
    import 'package:example/main.dart';
    import 'package:flutter_test/flutter_test.dart';
    import 'package:integration_test/integration_test.dart';
    
    void main() {
      IntegrationTestWidgetsFlutterBinding.ensureInitialized();
    
      testWidgets('interacts with the orange website in a webview', (tester) async {
        await tester.pumpWidget(ExampleApp());
    
        await tester.tap(find.text('Open webview (Hacker News)'));
    
        await tester.pumpAndSettle(Duration(seconds: 10));
      });
    }
    ```
    
    </details> 

1. Start an Android emulator

    I tested on Pixel 6, API level 31, hardware rendering enabled, and plentiful of resources available (4GB ram, 4GB VM heap, 6GB internal storage), system image: `system-images;android-31;google_apis;arm64-v8a`). I also have a fast and stable internet connection, so that's very likely not problem.

1. Run the test with `flutter test integration_test/webview_hackernews_test.dart` and observe that **the WebView is not loaded** (see video below), even though the logs say "100% loaded"

### Expected results

I expect the WebView to load the same as if the app was running normally.

### Actual results

The WebView doesn't load.

This is an important problem in [the Patrol framework](https://github.com/leancodepl/patrol) – it integrates with native tooling (UIAutomator, XCUITest) to make it possible to interact with native UI (permission dialogs, notifications, webviews) from normal Dart test code. This problem makes our webview interaction feature flaky.

---

I did a fair share of debugging of this, and it was an quite uncanny experience ([mainly in this issue](https://github.com/leancodepl/patrol/issues/244)). There are differences between e.g. OS versions, and hardware rendering enabled/disabled. I think creating this issue and waiting for somebody from the Flutter team to respond is the best I can do right now.

I'm also curious to hear some details:
- if/how the different underlying Platform View implementations ([Texture Layer Hybrid Composition](https://github.com/flutter/flutter/wiki/Texture-Layer-Hybrid-Composition), [Hybrid Composition](https://github.com/flutter/flutter/wiki/Hybrid-Composition), [Virtual Display](https://github.com/flutter/flutter/wiki/Virtual-Display)) might affect this bug.
- how Engine's standard rendering pipeline (triggered by `pump()` in tests) works with these different Platform Views implementations? According to my testing/trial&error, `pump`ing is a separate mechanism and is not required to display a webview (because it's a Platform View).
- What could be the cause of this problem?


### Screenshots or Video

<details>
<summary>Screenshots / Video demonstration</summary>

`flutter test integration_test/webview_hackernews_test.dart` (doesn't work)

https://github.com/flutter/flutter/assets/40357511/4d27a39a-9211-4f95-8f2f-005d1c628d5a

---

`flutter run` (works)

https://github.com/flutter/flutter/assets/40357511/42837e87-02c4-46b0-a3f4-ad4945015c50

---
 
`flutter run integration_test/webview_hackernews_test.dart` - incredibly flaky:

- usually, works after Hot Restart (`R` key) except the first time
- sometimes doesn't work during a few first Hot Restarts
- sometimes no amount of Hot Restarts helps

https://github.com/flutter/flutter/assets/40357511/1e165fc8-36b7-48df-ba32-ce13a04efbfd



</details>


### Logs

<details><summary>Logs</summary>

```console
$ flutter test integration_test/webview_hackernews_test.dart
00:00 +0: loading /Users/bartek/dev/leancode/patrol/packages/patrol/example/integration_test/webview_hackernews_test.dart                                                                                        R00:10 +0: loading /Users/bartek/dev/leancode/patrol/packages/patrol/example/integration_test/webview_hackernews_test.dart                                                                                    9.8s
✓  Built build/app/outputs/flutter-apk/app-debug.apk.
00:11 +0: loading /Users/bartek/dev/leancode/patrol/packages/patrol/example/integration_test/webview_hackernews_test.dart                                                                                   555ms
00:13 +0: interacts with the orange website in a webview
WebView progress: 10
WebView started loading: https://news.ycombinator.com/
WebView progress: 22
WebView progress: 70
WebView progress: 80
WebView progress: 100
WebView progress: 100
WebView finished loading: https://news.ycombinator.com # but the WebView is not visible!
```

</details>


### Flutter Doctor output

<details><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.10.6, on macOS 13.4.1 22F770820d darwin-arm64, locale en-PL)
    • Flutter version 3.10.6 on channel stable at /Users/bartek/fvm/versions/3.10.6
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision f468f3366c (7 days ago), 2023-07-12 15:19:05 -0700
    • Engine revision cdbeda788a
    • Dart version 3.0.6
    • DevTools version 2.23.1

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
    • Android SDK at /Users/bartek/androidsdk
    • Platform android-33, build-tools 33.0.1
    • ANDROID_HOME = /Users/bartek/androidsdk
    • Java binary at: /Users/bartek/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/222.4459.24.2221.10121639/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.3.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14E300c
    • CocoaPods version 1.12.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.2)
    • Android Studio at /Users/bartek/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/222.4459.24.2221.10121639/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 17.0.6+0-17.0.6b802.4-9586694)

[✓] IntelliJ IDEA Ultimate Edition (version 2023.1.4)
    • IntelliJ at /Users/bartek/Applications/JetBrains Toolbox/IntelliJ IDEA Ultimate.app
    • Flutter plugin version 74.0.4
    • Dart plugin version 231.9161.14

[✓] IntelliJ IDEA Ultimate Edition (version 2023.1.4)
    • IntelliJ at /Users/bartek/Library/Application Support/JetBrains/Toolbox/apps/IDEA-U/ch-0/231.9225.16/IntelliJ IDEA.app
    • 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

[✓] VS Code (version 1.80.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.68.0

[✓] Connected device (2 available)
    • macOS (desktop) • macos  • darwin-arm64   • macOS 13.4.1 22F770820d darwin-arm64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 114.0.5735.198

[✓] Network resources
    • All expected network resources are available.

• No issues found!
```

</details>