How to get redirect URL in dart/flutter?

Viewed 13197

I'm building an app that shows an image taken from source.unsplash. My request url is:

https://source.unsplash.com/random/`$widthx$height`

Then the service redirects to some specific image url picked fitting my width and height.

I can show the image with:
Image.network(url above),
but I cannot access the new redirected url for some other parts of my code which is really necessary. Is there a way to get it?

Thanks in advance

Something I'm searching for is like

Http.Response response = await Http.get(url);
print(response.finalRedirectURL);
3 Answers

It would be better if you use api.unsplash.com and not source.

If followRedirects is true, there's no way according to the docs to get the final redirected URL, so maybe post a github issue for this. See: https://pub.dev/documentation/http/latest/http/Response-class.html

The only way I see this happening is making followRedirects: false, will give you a response headers with location as a key that gives you the next redirect. You'd have to write a loop to keep going till the status code changes from 302 to something else.

Hope this helps.

For my own project, I was also not able to find any method from flutter/dart side.

However, I was able to find the location in response.headers. Maybe this can work.

enter image description here

  Future<String?> getUrlLocation(String url) async {
    final client = HttpClient();
    var uri = Uri.parse(url);
    var request = await client.getUrl(uri);
    request.followRedirects = false;
    var response = await request.close();
    return response.headers.value(HttpHeaders.locationHeader);
  }
Related