getUrl function

Future<Uri?> getUrl(
  1. String? url
)

Gets the URL of a given url and follows redirects.

This function is used to get the final URL of a given URL. It is used in the QuillEditor widget to open links in the browser. This function is necessary because the Quill editor does not work well with URLs that have redirects, most notably shortened Google Forms links.

Implementation

Future<Uri?> getUrl(String? url) async {
  if (url == null || url == '') return null;
  if (kIsWeb) {
    return Uri.parse(url);
  } else {
    final client = HttpClient();
    Uri uri = Uri.parse(url);
    HttpClientRequest request = await client.getUrl(uri);
    request.followRedirects = false;
    HttpClientResponse response = await request.close();
    for (var i = 0; i < 5; i++) {
      if (!response.isRedirect) {
        break;
      }
      response.drain();
      final location = response.headers.value(HttpHeaders.locationHeader);
      if (location != null) {
        uri = uri.resolve(location);
        request = await client.getUrl(uri);
        request.followRedirects = false;
        response = await request.close();
      }
    }
    return uri;
  }
}