I'm trying to get use HttpResponse.getString()
to fetch some data but I can't get it to import. I'm using the Dart VM.
I've tried
import 'dart:html'
which gives me Error: Not found: 'dart:html'
import 'package:http/http.dart
but this package does not have the HttpRequest
classimport 'dart:io'
which has the class but not the getString()
methodHere is my code
void main() async {
Future<String> data = HttpRequest.getString('localhost:8000');
print(data);
}
Why can't I access this class and method?
How are you running your program?
dart:html
is only available for applications running inside a browser.package:http
is not the same as dart:html
and does therefore have other classes. But you can achieve the same by using that package.dart:io
is only available when running your application by the Dart VM. But you can use this to achieve the same but you need to write the code differently.Since you get the error Error: Not found: 'dart:html'
I assume you are trying to get this working in the Dart VM.
You can do it like this if you want to use the http
package which I think it the easiest way to get what you want:
import 'package:http/http.dart' as http;
Future<void> main() async {
Future<String> data = http.read('localhost:8000');
print(await data);
}
And if you want to use dart:io
it can be done like this:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final clientRequest = await HttpClient().getUrl(Uri.parse('localhost:8000'));
final clientResponse = await clientRequest.close();
final data = await clientResponse
.transform(const Utf8Decoder())
.fold<StringBuffer>(
StringBuffer(), (buffer, element) => buffer..write(element));
print(data.toString());
}