flutter / flutter

Flutter makes it easy and fast to build beautiful apps for mobile and beyond
https://flutter.dev
BSD 3-Clause "New" or "Revised" License
162.19k stars 26.64k forks source link

When the page is closing, the unfinished webview crashes on iOS #146679

Closed rain9155 closed 1 month ago

rain9155 commented 1 month ago

Steps to reproduce

I put the webview on a page and then load a URL. When the URL is not yet fully loaded, I immediately close the page and the app will crash

Expected results

App crash

Actual results

The page was closed normally

Code sample

Code sample ```dart class _WebViewRouteState extends State{ bool _isLoading = true; late WebViewController _controller; @override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate( NavigationDelegate( onWebResourceError: (error){ LogUtil.printString(WebViewRoute.name, 'onWebResourceError: code = ${error.errorCode}, des = ${error.description}, url = ${error.url}'); }, onPageStarted: (url){ LogUtil.printString(WebViewRoute.name, 'onPageStarted: url = $url'); if(!_isLoading){ setState(() { _isLoading = true; }); } }, onPageFinished: (url){ LogUtil.printString(WebViewRoute.name, 'onPageFinished: url = $url'); if(_isLoading){ setState(() { _isLoading = false; }); } } ) ); } @override Widget build(BuildContext context) { var arguments = ModalRoute.of(context)!.settings.arguments as Map; String? title = arguments[KEY_TITLE]; String? url = arguments[KEY_URL]; return Scaffold( appBar: _buildAppBar(context, title, url) as PreferredSizeWidget?, body: _buildBody(url), ); } Widget _buildAppBar(BuildContext context, String? title, String? url) { return CommonAppBar( title: CommonTitle(title ?? ''), actions: [ CommonAction( icon: Icons.share_outlined, tooltip: AppLocalizations.of(context).share, onPressed: () => Share.share(url ?? "") ), CommonAction( icon: Icons.open_in_browser_outlined, tooltip: AppLocalizations.of(context).browser, onPressed: () => launchUrl(Uri.parse(url ?? "")) ), CommonAction( icon: Icons.refresh, tooltip: AppLocalizations.of(context).refresh, onPressed: (){ if(_isLoading){ ToastUtil.showSnackBar(context, msg: AppLocalizations.of(context).loading); return; } setState(() { _isLoading = true; }); _controller.reload(); } ) ], onBack: back, ); } Widget _buildBody(String? requestUrl) { _controller.currentUrl().then((url) { if(CommonUtil.isTextEmpty(url)) { LogUtil.printString(WebViewRoute.name, "start load $requestUrl"); _controller.loadRequest(Uri.parse(requestUrl ?? "")); } }); return PopScope( canPop: false, onPopInvoked: (didPop) { if(!didPop) { back().then((value) { if(value) { Navigator.of(context).pop(); } }); } }, child: Stack( children: [ WebViewWidget(controller: _controller), if(_isLoading) LinearLoadingWidget() ], ), ); } Future back() async { if(CommonUtil.isTextEmpty(await _controller.currentUrl())) { return true; } if(!await _controller.canGoBack()){ return true; } _controller.goBack(); return false; } } ```

Screenshots or Video

Screenshots / Video demonstration https://github.com/flutter/flutter/assets/38580832/ad030e6a-2cf6-4ffe-b2bc-b6a6e78df08a

Logs

Logs ```console ------------------------------------- Translated Report (Full Report Below) ------------------------------------- Incident Identifier: 4FDE8F6D-40B9-4BAD-A1BD-113185F02565 CrashReporter Key: E4A0BC97-F39A-A54D-1840-1828AE18BA27 Hardware Model: MacBookPro18,1 Process: Runner [62426] Path: /Users/USER/Library/Developer/CoreSimulator/Devices/495C73C2-222B-43D6-82A8-DC3CB44AD892/data/Containers/Bundle/Application/214C107D-758B-4DCF-B342-758BD72C5DEF/Runner.app/Runner Identifier: com.example.flutterGithubApp Version: 2.0.0 (2) Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd_sim [61629] Coalition: com.apple.CoreSimulator.SimDevice.495C73C2-222B-43D6-82A8-DC3CB44AD892 [41172] Responsible Process: SimulatorTrampoline [1327] Date/Time: 2024-04-12 16:38:43.6587 +0800 Launch Time: 2024-04-12 16:37:18.1100 +0800 OS Version: macOS 14.1.1 (23B81) Release Type: User Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 6 Abort trap: 6 Terminating Process: Runner [62426] Triggered by Thread: 0 Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x101d08a4c __pthread_kill + 8 1 libsystem_pthread.dylib 0x101c431d0 pthread_kill + 256 2 libsystem_c.dylib 0x1801655c0 abort + 104 3 libc++abi.dylib 0x1802a7798 abort_message + 128 4 libc++abi.dylib 0x180298eec demangling_terminate_handler() + 300 5 libobjc.A.dylib 0x180063498 _objc_terminate() + 124 6 libc++abi.dylib 0x1802a6c70 std::__terminate(void (*)()) + 12 7 libc++abi.dylib 0x1802a98dc __cxxabiv1::failed_throw(__cxxabiv1::__cxa_exception*) + 32 8 libc++abi.dylib 0x1802a989c __cxa_throw + 132 9 libobjc.A.dylib 0x180087eec objc_exception_throw + 368 10 Foundation 0x180d2dfd8 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 184 11 webview_flutter_wkwebview 0x101dc3d78 __53-[FWFNavigationDelegate webView:didFinishNavigation:]_block_invoke + 156 (FWFNavigationDelegateHostApi.m:178) 12 webview_flutter_wkwebview 0x101db1f90 __115-[FWFWKNavigationDelegateFlutterApi didFinishNavigationForDelegateWithIdentifier:webViewIdentifier:URL:completion:]_block_invoke + 248 (FWFGeneratedWebKitApis.m:1951) 13 Flutter 0x1053bc088 __48-[FlutterBasicMessageChannel sendMessage:reply:]_block_invoke + 92 14 Flutter 0x104ded430 std::_fl::__function::__func>)::$_0>, std::_fl::allocator>)::$_0>>, void ()>::operator()() + 60 15 Flutter 0x1050bb178 fml::MessageLoopImpl::FlushTasks(fml::FlushType) + 156 16 Flutter 0x1050c1d48 fml::MessageLoopDarwin::OnTimerFire(__CFRunLoopTimer*, fml::MessageLoopDarwin*) + 32 17 CoreFoundation 0x18040f588 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 28 18 CoreFoundation 0x18040f244 __CFRunLoopDoTimer + 948 19 CoreFoundation 0x18040e8e0 __CFRunLoopDoTimers + 284 20 CoreFoundation 0x18040902c __CFRunLoopRun + 1796 21 CoreFoundation 0x180408514 CFRunLoopRunSpecific + 572 22 GraphicsServices 0x18ef06ae4 GSEventRunModal + 160 23 UIKitCore 0x1853e8040 -[UIApplication _run] + 868 24 UIKitCore 0x1853ebcc8 UIApplicationMain + 124 25 Runner 0x100d17e0c main + 64 (AppDelegate.swift:5) 26 dyld_sim 0x100e9d544 start_sim + 20 27 dyld 0x100f320e0 start + 2360 ```

Flutter Doctor output

Doctor output ```console $ flutter doctor -v [✓] Flutter (Channel stable, 3.19.5, on macOS 14.1.1 23B81 darwin-arm64, locale zh-Hans-CN) • Flutter version 3.19.5 on channel stable at /Users/bytedance/Documents/source/flutter/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 300451adae (2 weeks ago), 2024-03-27 21:54:07 -0500 • Engine revision e76c956498 • Dart version 3.3.3 • DevTools version 2.31.1 [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0) • Android SDK at /Users/bytedance/Library/Android/sdk • Platform android-34, build-tools 34.0.0 • ANDROID_HOME = /Users/bytedance/Library/Android/sdk • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231) • All Android licenses accepted. [✓] Xcode - develop for iOS and macOS (Xcode 15.3) • Xcode at /Applications/Xcode.app/Contents/Developer • Build 15E204a • CocoaPods version 1.15.2 [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome [✓] Android Studio (version 2022.3) • 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 17.0.6+0-17.0.6b829.9-10027231) [✓] VS Code (version 1.88.0) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.86.0 [✓] Connected device (5 available) • EML AL00 (mobile) • CLB0218329006836 • android-arm64 • Android 10 (API 29) • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64 • Android 13 (API 33) (emulator) • iPhone 15 Pro Max (mobile) • 495C73C2-222B-43D6-82A8-DC3CB44AD892 • ios • com.apple.CoreSimulator.SimRuntime.iOS-17-4 (simulator) • macOS (desktop) • macos • darwin-arm64 • macOS 14.1.1 23B81 darwin-arm64 • Chrome (web) • chrome • web-javascript • Google Chrome 123.0.6312.123 [✓] Network resources • All expected network resources are available. • No issues found! ```
darshankawar commented 1 month ago

@rain9155 Can you provide complete runnable reproducible code sample without third party implementation or custom implementation, which we can directly run to verify this further ?

moffatman commented 1 month ago

Looks like webview plugin crash because your NavigationDelegate.onPageFinished threw an exception. It's probably because you call setState(() {}), which will throw an exception after the route is closed, because it has no context mounted.

To fix

  1. Please override dispose() and dispose() the controller when the route is closed
  2. Please check mounted before calling setState(() {})
rain9155 commented 1 month ago

@moffatman Thank you, I checked the code and it's the issue you mentioned. After the webview was loaded, the page just closed and called the setState method. I solved this problem by checking the mounted state

moffatman commented 1 month ago

OK, just remember to dispose the controller too @rain9155

github-actions[bot] commented 2 weeks ago

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.