launchUrl function

Future<void> launchUrl(
  1. Uri url, {
  2. bool prefersDeepLink = false,
  3. CustomTabsOptions? customTabsOptions,
  4. SafariViewControllerOptions? safariVCOptions,
})

Passes url with options to the underlying platform for launching a custom tab.

  • On Android, the appearance and behavior of Custom Tabs can be customized using the customTabsOptions parameter.
  • On iOS, the appearance and behavior of SFSafariViewController can be customized using the safariVCOptions parameter.
  • For web, customization options are not available.

If customTabsOptions or safariVCOptions are null, the URL will be launched in an external browser on mobile platforms.

Example of launching Custom Tabs:

final theme = ...;
try {
  await launchUrl(
    Uri.parse('https://flutter.cn'),
    customTabsOptions: CustomTabsOptions(
      colorSchemes: CustomTabsColorSchemes.defaults(
        toolbarColor: theme.colorScheme.surface,
      ),
      urlBarHidingEnabled: true,
      showTitle: true,
      closeButton: CustomTabsCloseButton(
        icon: CustomTabsCloseButtonIcons.back,
      ),
    ),
    safariVCOptions: SafariViewControllerOptions(
      preferredBarTintColor: theme.colorScheme.surface,
      preferredControlTintColor: theme.colorScheme.onSurface,
      barCollapsingEnabled: true,
      dismissButtonStyle: SafariViewControllerDismissButtonStyle.close,
    ),
  );
} catch (e) {
  // If the URL launch fails, an exception will be thrown. (For example, if no browser app is installed on the Android device.)
}

Example of launching an external browser:

try {
  await launchUrl(Uri.parse('https://flutter.cn'));
} catch (e) {
  // An exception is thrown if browser app is not installed on Android device.
}

Implementation

Future<void> launchUrl(
  Uri url, {
  bool prefersDeepLink = false,
  CustomTabsOptions? customTabsOptions,
  SafariViewControllerOptions? safariVCOptions,
}) async {
  if (url.scheme != 'http' && url.scheme != 'https') {
    throw PlatformException(
      code: 'NOT_A_WEB_SCHEME',
      message: 'Flutter Custom Tabs only supports URL of http or https scheme.',
    );
  }

  await CustomTabsPlatform.instance.launch(
    url.toString(),
    prefersDeepLink: prefersDeepLink,
    customTabsOptions: customTabsOptions,
    safariVCOptions: safariVCOptions,
  );
}