pLaunchURL function

Future<void> pLaunchURL(
  1. String action, {
  2. URLType urlType = URLType.web,
  3. LaunchMode? mode,
  4. String? webOnlyWindowName,
  5. WebViewConfiguration? webViewConfiguration,
  6. String? emailBody,
  7. bool setUrlCorrection = false,
  8. bool openInGoogleIfError = true,
})

Implementation

Future<void> pLaunchURL(String action,
    {URLType urlType = URLType.web,
    LaunchMode? mode,
    String? webOnlyWindowName,
    WebViewConfiguration? webViewConfiguration,
    String? emailBody,
    bool setUrlCorrection = false,
    bool openInGoogleIfError = true}) async {
  if (action == Str.na) {
    pShowToast(message: "Invalid Content");
  } else {
    String url = '';
    String error = '';
    switch (urlType) {
      case URLType.call:
        url = 'tel:$action';
        error = 'Could not dial $action';
        break;
      case URLType.sms:
        url = 'sms:$action';
        error = 'Could not sms on $action';
        break;
      case URLType.web:
        url = action;

        if (setUrlCorrection) {
          if (action.toLowerCase().startsWith('http')) {
            url = action;
          } else {
            if (action.toLowerCase().startsWith('www.')) {
              url = 'http://${action.substring(4)}';
            } else {
              error = 'Could not open $action';
            }
          }
        }

        error = 'Could not open $action';
        break;
      case URLType.email:
        final Uri params = Uri(
          scheme: 'mailto',
          path: action,
          query: emailBody ?? '', //add subject and body here
        );
        url = params.toString();
        error = 'Could not send an email on $action';
        break;
    }

    debugPrint(url);
    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrlBody(url, mode, webOnlyWindowName, webViewConfiguration);
    } else {
      if (openInGoogleIfError) {
        if (urlType == URLType.web) {
          String customSearch = 'https://www.google.com/search?q=$url';
          await launchUrlBody(
              customSearch, mode, webOnlyWindowName, webViewConfiguration);
        }
      } else {
        pShowToast(message: error);
      }
    }
  }
}