openURL function

Future<void> openURL({
  1. required String url,
  2. dynamic callback()?,
})

Attempts to open the given url using a platform-specific method channel.

Validates that the URL has a valid scheme (http or https) before attempting to launch it. If the URL is invalid, logs an error.

If the URL is successfully launched and a callback is provided, executes the callback.

Example:

await openURL(
  url: 'https://example.com',
  callback: () => logFile(key: 'URL launched!', name: 'open url'),
);

url: The web URL to open (must start with 'http://' or 'https://'). callback: Optional function to run after successfully launching the URL.

Uses a platform channel named _platform which should be initialized elsewhere.

Logs errors using logFile on failure or invalid URL.

Implementation

Future<void> openURL({required String url, Function()? callback}) async {
  final uri = Uri.parse(url);
  bool isAvailable =
      uri.hasScheme && (uri.scheme == 'http' || uri.scheme == 'https');
  if (isAvailable) {
    try {
      await _platform.invokeMethod('launchURL', {'url': url});

      // If the callback is provided, execute it
      if (callback != null) {
        callback();
      }
    } on PlatformException catch (e) {
      logFile(message: "Failed to launch URL: ${e.message}", name: "open url");
    }
  } else {
    logFile(message: "url: $url is invalid", name: "open url");
  }
}