Search code examples
flutterbrowserinappbrowser

Flutter (ChromeSafariBrowser._throwIsAlreadyOpened error)


I'm using a library called flutter_inappbrowser 1.2.1. With the help of this library i'm opening a browser and it work's well at first time, but after that if we try to open the browser again, it will throw error

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Exception: [Error: Cannot open https://www.abcd.com/xyzal.html! The browser is already opened.]

The code used for the action is provided below.

Center(
child: InkWell(
onTap: () {
chromeSafariBrowser
    .open(url, options: {
"addShareButton": true,
"toolbarBackgroundColor": "#FFFFFF",
"dismissButtonStyle": 1,
"preferredBarTintColor": "#FFFFFF",
"instantAppsEnabled": false
}, optionsFallback: {
"toolbarTopBackgroundColor": "#FFFFFF",
"closeButtonCaption": "Close"
});
},
child: Text(
'Read More...',
style: TextStyle(
color: Color(0xFF38969A),
fontSize: 16.0,
decoration: TextDecoration.underline,
fontWeight: FontWeight.bold),
),
))


class MyInAppBrowser extends InAppBrowser {
  @override
  Future onLoadStart(String url) async {
    print("\n\nStarted $url\n\n");
  }

  @override
  Future onLoadStop(String url) async {
    print("\n\nStopped $url\n\n");
  }

  @override
  void onLoadError(String url, int code, String message) {
    print("\n\nCan't load $url.. Error: $message\n\n");
  }

  @override
  void onExit() {
    print("\n\nBrowser closed!\n\n");
  }
}

MyInAppBrowser inAppBrowserFallback = new MyInAppBrowser();

class MyChromeSafariBrowser extends ChromeSafariBrowser {
  MyChromeSafariBrowser(browserFallback) : super(browserFallback);

  @override
  void onOpened() {
    print("ChromeSafari browser opened");
  }

  @override
  void onLoaded() {
    print("ChromeSafari browser loaded");
  }

  @override
  void onClosed() {
    print("ChromeSafari browser closed");
  }
}

MyChromeSafariBrowser chromeSafariBrowser =
    new MyChromeSafariBrowser(inAppBrowserFallback);

Any help will be appreciated, Thank you.


Solution

  • I have found the solution, posting it here as it may help someone in future.

    Solution is that instead of calling chromeSafariBrowser.open(...) directly call MyChromeSafariBrowser(inAppBrowserFallback).open(...). New instance will be created and all will work smoothly. Don't know whether it is the proper solution or not.

    Eg:

    onTap: ()  {
    MyChromeSafariBrowser(inAppBrowserFallback)
        .open(newsData.url, options: {
    "addShareButton": true,
    "toolbarBackgroundColor": "#FFFFFF",
    "dismissButtonStyle": 1,
    "preferredBarTintColor": "#FFFFFF",
    "instantAppsEnabled": false
    }, optionsFallback: {
    "toolbarTopBackgroundColor": "#FFFFFF",
    "closeButtonCaption": "Close"
    });
    },