Skip to content

webview_flutter NavigationDelegate onUrlChange throw NSInternalInconsistencyException  #128422

@MeiYuLong

Description

@MeiYuLong

Is there an existing issue for this?

Steps to reproduce

I need to listen for URL changes;(ios),so used 'onUrlChange', but it's throw 'NSInternalInconsistencyException InstanceManager does not contain an NSURL with identifier: 65567' when UrlChanged.

output :
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(NSInternalInconsistencyException, InstanceManager does not contain an NSURL with identifier: 65567, null, null) #0 NSUrlHostApi.getAbsoluteString (package:webview_flutter_wkwebview/src/common/web_kit.g.dart:2596:7) <asynchronous suspension> #1 WebKitWebViewController._webView.<anonymous closure>.<anonymous closure> (package:webview_flutter_wkwebview/src/webkit_webview_controller.dart:174:48) <asynchronous suspension>

Expected results

Expected to behave normally when changing

Actual results

I need to listen for URL changes;(ios),so used 'onUrlChange', but it's throw 'NSInternalInconsistencyException InstanceManager does not contain an NSURL with identifier: 65567' when UrlChanged.

Code sample

Code sample
class WebView extends StatefulWidget {
  const WebView(
      {Key? key,
      this.onTitleChanged,
      required this.url,
      this.onUtlChanged,
      this.onControllerDone})
      : super(key: key);

  final String url;
  final ValueChanged<WebViewController>? onControllerDone;
  final ValueChanged<String>? onTitleChanged;
  final ValueChanged<String>? onUtlChanged;

  @override
  State<WebView> createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  late final WebViewController _controller;
  late final WebViewCookieManager cookieManager = WebViewCookieManager();

  double _progress = 0.0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initializeController();
    CookieManager.setCookie(cookieManager, widget.url).then((_) async {
      await _controller.clearCache();
      _controller.loadRequest(Uri.parse(widget.url));
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    debugPrint('webview dispose');
    // _controller.
    super.dispose();
  }

  void _initializeController() {
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }
    _controller = WebViewController.fromPlatformCreationParams(params)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(ThemeColors.background);
    JavaScriptManager.add(_controller);
    _addNavigationDelegate();
    if (_controller.platform is AndroidWebViewController) {
      AndroidWebViewController.enableDebugging(true);
      (_controller.platform as AndroidWebViewController)
          .setMediaPlaybackRequiresUserGesture(false);
    }
  }

  void _addNavigationDelegate() {
    _controller.setNavigationDelegate(
      NavigationDelegate(
        onProgress: (int progress) {
          debugPrint('progress $progress');
          if (mounted) {
            double value = progress.toDouble() * 0.01;
            _progress = value == 1.0 ? 0.0 : value;
            setState(() => {});
          }
        },
        onPageStarted: (String url) {
          debugPrint('onPageStarted $url');
          if (widget.onControllerDone != null) {
            widget.onControllerDone!(_controller);
          }
        },
        onPageFinished: (String url) async {
          debugPrint('onPageFinished $url');
          final title = await _controller.getTitle();
          debugPrint('onPageFinished$title');
          if (widget.onTitleChanged != null && title != null && mounted) {
            widget.onTitleChanged!(title);
          }
        },
        onNavigationRequest: (NavigationRequest request) {
          debugPrint('onNavigationRequest');
          return NavigationDecision.navigate;
        },
        onWebResourceError: (WebResourceError error) {
          debugPrint('''
Page resource error:
  code: ${error.errorCode}
  description: ${error.description}
  errorType: ${error.errorType}
  isForMainFrame: ${error.isForMainFrame}
          ''');
          showError(error);
        },
        onUrlChange: (UrlChange change) {
          if (widget.onUtlChanged != null) {
            widget.onUtlChanged!(change.url.toString());
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        WebViewWidget(controller: _controller),
        Align(
          alignment: Alignment.topCenter,
          child: _buildProgress(),
        )
      ],
    );
  }

  Widget _buildProgress() {
    return LinearProgressIndicator(
      value: _progress,
    );
  }

  void showError(WebResourceError error) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(error.description),
      backgroundColor: ThemeColors.theme,
      padding: const EdgeInsets.all(10),
    ));
  }
}

Screenshots or Video

Screenshots / Video demonstration

image

image

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
[✓] Flutter (Channel master, 3.8.0-1.0.pre.4, on macOS 13.4 22F66 darwin-x64, locale bo-CN)
    • Flutter version 3.8.0-1.0.pre.4 on channel master at /Users/yulongmei/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision a752c2f154 (4 months ago), 2023-02-01 00:41:16 -0500
    • Engine revision 1703a39662
    • Dart version 3.0.0 (build 3.0.0-187.0.dev)
    • DevTools version 2.20.1
    • Pub download mirror https://pub.flutter-io.cn
    • Flutter download mirror https://storage.flutter-io.cn

[✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
    • Android SDK at /Users/yulongmei/Library/Android/sdk
    • Platform android-33, build-tools 32.0.0
    • ANDROID_HOME = /Users/yulongmei/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/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 14.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14C18
    • 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.78.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (3 available)
    • iPhone 14 Pro Max (mobile) • 79F8F18A-0B96-43D2-82A8-529B81DDFADB • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator)
    • macOS (desktop)            • macos                                • darwin-x64     • macOS 13.4 22F66 darwin-x64
    • Chrome (web)               • chrome                               • web-javascript • Google Chrome 114.0.5735.106

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

Metadata

Metadata

Assignees

Labels

P1High-priority issues at the top of the work listc: contributor-productivityTeam-specific productivity, code health, technical debt.c: regressionIt was better in the past than it is nowp: webviewThe WebView pluginpackageflutter/packages repository. See also p: labels.platform-iosiOS applications specificallyr: fixedIssue is closed as already fixed in a newer version

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions