Repository: flutter
Issue: WebView.destroy() called while WebView is still attached to window. Potential memory leak?
Labels: platform-android,engine,a: platform-views,has reproducible steps,P2,found in release: 3.3,found in release: 3.7,team-android,triaged-android

## Description 
After hiding a web view, `WebView.destroy() called while WebView is still attached to window` is logged. 

## Steps to Reproduce
```dart 
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: AppPage());
  }
}

class AppPage extends StatefulWidget {
  const AppPage({super.key});

  @override
  State<AppPage> createState() => _AppPageState();
}

class _AppPageState extends State<AppPage> {
  bool _showWebView = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        alignment: Alignment.center,
        children: [
          if (_showWebView) const WebviewExample(),
          Container(
            color: const Color.fromARGB(226, 255, 255, 255),
          ),
          TextButton(
            onPressed: () {
              setState(() {
                _showWebView = !_showWebView;
              });
            },
            child: const Text(
              "Show Webview",
              style: TextStyle(color: Colors.black),
            ),
          ),
        ],
      ),
    );
  }
}

class WebviewExample extends StatefulWidget {
  const WebviewExample({super.key});

  @override
  State<WebviewExample> createState() => _WebviewExampleState();
}

class _WebviewExampleState extends State<WebviewExample> {
  final controller = WebViewController.fromPlatformCreationParams(
      const PlatformWebViewControllerCreationParams());

  @override
  void initState() {
    super.initState();

    controller
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (String url) {},
        ),
      )
      ..loadRequest(Uri.parse("https://www.example.com/"));
  }

  @override
  Widget build(BuildContext context) {
    return WebViewWidget(controller: controller);
  }
}

```
1. Toggle the "Show Webview" button multiple times and look at console


## Logs

<details>
<summary>Logs</summary>

```
  +34 ms] Syncing files to device sdk gphone64 arm64...
[        ] Compiling dart to kernel with 0 updated files
[        ] Processing bundle.
[        ] <- recompile package:bug/main.dart de4b6503-955f-4203-9010-2f89509c83a8
[        ] <- de4b6503-955f-4203-9010-2f89509c83a8
[        ] Bundle processing done.
[  +49 ms] Updating files.
[        ] DevFS: Sync finished
[        ] Syncing files to device sdk gphone64 arm64... (completed in 51ms)
[        ] Synced 0.0MB.
[        ] <- accept
[   +2 ms]



 Connected to _flutterView/0xb400007dcd0018d0.
[   +1 ms] Flutter run key commands.
[        ] r Hot reload. 🔥🔥🔥
[        ] R Hot restart.
[        ] h List all available interactive commands.
[        ] d Detach (terminate "flutter run" but leave application running).
[        ] c Clear the screen
[        ] q Quit (terminate the application on the device).
[        ] 💪 Running with sound null safety 💪
[        ] An Observatory debugger and profiler on sdk gphone64 arm64 is available at:
           http://127.0.0.1:63233/V7HZcV8YcOI=/
[ +124 ms] The Flutter DevTools debugger and profiler on sdk gphone64 arm64 is available at:
                    http://127.0.0.1:9101?uri=http://127.0.0.1:63233/V7HZcV8YcOI=/
[+18598 ms] I/WebViewFactory( 7242): Loading com.google.android.webview version 91.0.4472.114 (code
447211484)
[   +4 ms] D/nativeloader( 7242): Configuring classloader-namespace for other apk
/data/app/~~ctsuX7JjAntmd9A-GA0A1Q==/com.google.android.trichromelibrary_447211484-P_aLjgq6UA1BWC9Mf5crpw=
=/TrichromeLibrary.apk. target_sdk_version=31, uses_libraries=ALL,
library_path=/data/app/~~SXF7BX-3hyYesN7iQ_yoVA==/com.google.android.webview-FAbofLmMthUGtgorbIQ8tQ==/lib/
arm64:/data/app/~~SXF7BX-3hyYesN7iQ_yoVA==/com.google.android.webview-FAbofLmMthUGtgorbIQ8tQ==/WebViewGoog
le.apk!/lib/arm64-v8a:/data/app/~~ctsuX7JjAntmd9A-GA0A1Q==/com.google.android.trichromelibrary_447211484-P
_aLjgq6UA1BWC9Mf5crpw==/TrichromeLibrary.apk!/lib/arm64-v8a, permitted_path=/data:/mnt/expand
[   +2 ms] D/nativeloader( 7242): Configuring classloader-namespace for other apk
/data/app/~~SXF7BX-3hyYesN7iQ_yoVA==/com.google.android.webview-FAbofLmMthUGtgorbIQ8tQ==/WebViewGoogle.apk
. target_sdk_version=31, uses_libraries=,
library_path=/data/app/~~SXF7BX-3hyYesN7iQ_yoVA==/com.google.android.webview-FAbofLmMthUGtgorbIQ8tQ==/lib/
arm64:/data/app/~~SXF7BX-3hyYesN7iQ_yoVA==/com.google.android.webview-FAbofLmMthUGtgorbIQ8tQ==/WebViewGoog
le.apk!/lib/arm64-v8a:/data/app/~~ctsuX7JjAntmd9A-GA0A1Q==/com.google.android.trichromelibrary_447211484-P
_aLjgq6UA1BWC9Mf5crpw==/TrichromeLibrary.apk!/lib/arm64-v8a, permitted_path=/data:/mnt/expand
[  +35 ms] W/com.example.bu( 7242): Accessing hidden method Landroid/os/Trace;->isTagEnabled(J)Z
(unsupported, reflection, allowed)
[        ] W/com.example.bu( 7242): Accessing hidden method
Landroid/os/Trace;->traceBegin(JLjava/lang/String;)V (unsupported, reflection, allowed)
[        ] W/com.example.bu( 7242): Accessing hidden method Landroid/os/Trace;->traceEnd(J)V (unsupported,
reflection, allowed)
[        ] W/com.example.bu( 7242): Accessing hidden method
Landroid/os/Trace;->asyncTraceBegin(JLjava/lang/String;I)V (unsupported, reflection, allowed)
[        ] W/com.example.bu( 7242): Accessing hidden method
Landroid/os/Trace;->asyncTraceEnd(JLjava/lang/String;I)V (unsupported, reflection, allowed)
[  +12 ms] I/cr_LibraryLoader( 7242): Loaded native library version number "91.0.4472.114"
[        ] I/cr_CachingUmaRecorder( 7242): Flushed 6 samples from 6 histograms.
[  +90 ms] W/chromium( 7242): [WARNING:dns_config_service_android.cc(153)] Failed to read DnsConfig.
[  +20 ms] D/CompatibilityChangeReporter( 7242): Compat change id reported: 171228096; UID 10146; state:
ENABLED
[  +14 ms] W/com.example.bu( 7242): Accessing hidden method
Landroid/media/AudioManager;->getOutputLatency(I)I (unsupported, reflection, allowed)
[   +1 ms] D/HostConnection( 7242): createUnique: call
[        ] D/HostConnection( 7242): HostConnection::get() New Host Connection established
0xb400007d2cfdd550, tid 7365
[   +1 ms] W/cr_media( 7242): Requires BLUETOOTH permission
[        ] D/HostConnection( 7242): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1
ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1
ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan
ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings
ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache
ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator
ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8
ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands
ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3
GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing
ANDROID_EMU_gles_max_version_3_0 
[        ] D/EGL_emulation( 7242): eglCreateContext: 0xb400007d2cfdf7d0: maj 3 min 0 rcv 3
[        ] D/EGL_emulation( 7242): eglMakeCurrent: 0xb400007d2cfdf7d0: ver 3 0 (tinfo 0x7f5f7ab280) (first
time)
[   +2 ms] I/PlatformViewsController( 7242): Hosting view in view hierarchy for platform view: 0
[   +4 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[   +5 ms] D/EGL_emulation( 7242): eglCreateContext: 0xb400007d2cfdda90: maj 3 min 0 rcv 3
[  +28 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[   +9 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +16 ms] D/EGL_emulation( 7242): eglCreateContext: 0xb400007d2cfde390: maj 3 min 0 rcv 3
[ +145 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[+1048 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[        ] D/EGL_emulation( 7242): app_time_stats: avg=313.02ms min=7.98ms max=1048.29ms count=4
[   +2 ms] D/EGL_emulation( 7242): app_time_stats: avg=5001.14ms min=6.31ms max=18792.68ms count=4
[   +3 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +11 ms] D/EGL_emulation( 7242): app_time_stats: avg=643.41ms min=1.56ms max=18440.10ms count=31
[        ] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +17 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +15 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +16 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +16 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +15 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +17 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +15 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +17 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +15 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +17 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +15 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +17 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[  +15 ms] E/FrameEvents( 7242): updateAcquireFence: Did not find frame.
[ +801 ms] D/EGL_emulation( 7242): app_time_stats: avg=50.84ms min=12.77ms max=704.11ms count=20
[  +42 ms] W/cr_AwContents( 7242): WebView.destroy() called while WebView is still attached to window.
[  +23 ms] D/EGL_emulation( 7242): app_time_stats: avg=58.04ms min=3.70ms max=853.02ms count=16
[+121662 ms] Application finished.

(base) bug flutter analyze
Analyzing bug...                                                        
No issues found! (ran in 1.6s)

(base) bug flutter doctor -v
[✓] Flutter (Channel stable, 3.3.10, on macOS 12.2.1 21D62 darwin-arm, locale en-US)
    • Flutter version 3.3.10 on channel stable at /Users/davidhicks/Development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 135454af32 (3 weeks ago), 2022-12-15 07:36:55 -0800
    • Engine revision 3316dd8728
    • Dart version 2.18.6
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/davidhicks/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • ANDROID_HOME = /Users/davidhicks/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13F100
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • 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.12+0-b1504.28-7817840)

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.57.20221221

[✓] Connected device (3 available)
    • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64  • Android 12 (API 31) (emulator)
    • macOS (desktop)             • macos         • darwin-arm64   • macOS 12.2.1 21D62 darwin-arm
    • Chrome (web)                • chrome        • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
```

</details>

https://user-images.githubusercontent.com/59215665/210310539-d5efd6ca-47e0-437e-ae69-ccc5644c04c4.mov

I have limited knowledge of Android, but it appears others on the web have pointed to this causing [memory leaks in their applications](https://stackoverflow.com/questions/11995270/error-webview-destroy-called-while-still-attached). I'm not sure of the validity of this claim, but I wanted to bring it to your attention regardless. Thanks!