A cross-platform dart:io that works in all platforms (browsers, Flutter, and VM).
Licensed under the Apache License 2.0. Much of the source code is derived from Dart SDK, which was obtained under the BSD-style license of Dart SDK. See LICENSE file for details.
Other Pub packages in this repository include:
- chrome_os_io (adapter for Chrome OS sockets API)
- nodejs_io (adapter for Node.JS)
- test_io (helpers for unit tests)
- universal_html (cross-platform dart:html)
dependencies:
universal_io: ^1.0.0
The may also consider chrome_os_io (if you use Chrome OS) and nodejs_io (if you use Node.JS).
import 'package:universal_io/io.dart';
Future<void> main() async {
final httpClient = HttpClient();
final request = await httpClient.getUrl(Uri.parse("http://google.com"));
final response = await request.close();
}
In some situations, Dart development tools (your IDE) may give warnings, but your application
will compile fine. You can try to eliminate warnings by importing
"package:universal_io/prefer_universal/io.dart"
or "package:universal_io/prefer_sdk/io.dart"
HTTP client is implemented using XMLHttpRequest (XHR) (in dart:html, the class is HttpRequest).
XHR causes the following differences with dart:io:
- HTTP connection is created only after
request.close()
has been called. - Same-origin policy limitations. For making cross-origin requests, see documentation below.
If the HTTP request is cross-origin and Authorization header is present, the request will automatically use CORS credentials mode. For other requests, you can manually enable credentials mode using:
if (request is BrowserHttpClientRequest) {
request.credentialsMode = BrowserHttpClientCredentialsMode.include;
}
If any cross-origin request fails, error message contains a detailed description how to fix possible issues like missing cross-origin headers. The error messages look like:
BrowserHttpClient received an error from XMLHttpRequest (which doesn't tell
reason for the error).
HTTP method: PUT
URL: http://destination.com/path/example
Origin: http://source.com
Cross-origin request!
CORS 'credentials mode' is disabled (the browser will not send cookies).
You can enable 'credentials mode' with:
if (httpRequest is BrowserHttpClientRequest) {
httpRequest.credentialsMode = BrowserHttpClientCredentialsMode.include;
}
Did the server send the following mandatory headers?
* Access-Control-Allow-Origin: http://source.com
* OR '*'
* Access-Control-Allow-Methods: PUT
The underlying XHR supports streaming only for text responses. You can enable streaming by changing response type:
Future<void> main() async {
// ...
// Change response type
if (request is BrowserHttpClientRequest) {
request.responseType = BrowserHttpClientResponseType.text;
}
// Stream chunks
final response = await request.close();
response.listen((chunk) {
// ...
});
}
The implementation supports APIs such as:
Platform.isWindows
Platform.operatingSystem
Platform.locale