dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.11k stars 1.57k forks source link

Improve documentation on dart:html APIs (e.g., by pointing to MDN) #50443

Open moneer-muntazah opened 1 year ago

moneer-muntazah commented 1 year ago

Hi,

I have a PDF file that I need to download, and it requires an authentication token passed to the header. I've read about the Fetch API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch and is trying to use it in flutter.

The signature of fetch function in html_dart2js.dart is Future fetch(/*RequestInfo*/ input, [Map? init]) so I tried to use it like so

import 'dart:html' as html;
...
ElevatedButton(
            child: Text('fetch'),
            onPressed: () async {
              final r = await html.window.fetch({'<link to pdf file>')});
              final url = html.Url.createObjectUrl(await r.blob());
              final anchor = html.AnchorElement(href: url);
              anchor.download = 'test.pdf';
              anchor.click();
            },
          ),

I no longer get a type exception, but this always throws a FormatException whenever I pass in a url here is an output for trying to fetch a random image

ERROR - 2022-11-10 12:28:57.382828
GET /%7Bhttps://fileinfo.com/img/ss/xl/jpg_44.png%7D
Error thrown by handler.
FormatException: Scheme not starting with alphabetic character (at character 1)
%7Bhttps://fileinfo.com/img/ss/xl/jpg_44.png%7D

I guess there is an issue with url encoding. Or is my usage wrong?

Thanks

vsmenon commented 1 year ago

It does look like the url string is malformed - it starts with /%7B.

Note, Dart just forwards to the underlying browser API: https://developer.mozilla.org/en-US/docs/Web/API/fetch

The first argument is passed unmodified to the JS code. It should just be a string - that's not clear in your example. The error is coming from JS.

moneer-muntazah commented 1 year ago

Thank you so much I got it to work passing data like so


final r = await html.window.fetch(
                                                  pdfUrl,
                                                      {
                                                        'headers': {
                                                          'accessToken': accessToken
                                                        }
                                                      });
vsmenon commented 1 year ago

Thanks for the update. I'll repurpose this bug as a req to improve documentation.