user1334731
user1334731

Reputation: 81

How do I import dart:html & dart:io in the same class?

The code below "looks right", it compiles, but does not run, failing with the console message:

Cannot load Dart script dart:io
Failed to load resource

If I comment out the #import('dart:io');, wrong I believe, I get a compilation error, but it launches and not until I press the button, do I get the runtime error:

Internal error: 'http://127.0.0.1:3030/home/david/dart/samples/htmlIO/htmlIO.dart': Error: line 13 pos 26: type 'HttpClient' is not loaded
var connection = new HttpClient().get('www.google.com', 80, '/');

... which is expected.

So my question is: How do I import dart:html & dart:io in the same class?

#import('dart:html');
#import('dart:io');

class htmlIO {

  ButtonElement _aButton;

  htmlIO() {
  }

  void handlePress(Event e) {
    var connection = new HttpClient().get('www.google.com', 80, '/');
    write('made it');
  }

  void run() {
    _aButton = document.query("#aButton");
    _aButton.on.click.add(handlePress);
    write("Hello World!");
  }

  void write(String message) {
    // the HTML library defines a global "document" variable
    document.query('#status').innerHTML = message;
  }
}

void main() {
  new htmlIO().run();
}

Upvotes: 7

Views: 6564

Answers (2)

Seth Ladd
Seth Ladd

Reputation: 120439

Short answer, you can't. As Chris mentions, dart:io library is only for server libraries.

I see you're trying to connect to an HTTP service in your HTML app. You should check out the HttpRequest library. Here's a link to examples: http://c.dart-examples.com/api/dart-html/interface/eventtarget/httprequest/asynchronous

import 'dart:html';
import 'dart:convert';

void onSuccess(ProgressEvent event, HttpRequest request) {
  print(event.loaded); // 0
  print(request.statusText); // ok
  print(request.responseText); // "(resource text)"
}

/**
 * test.txt file must be of the same origin
 * Or the response header must contain "Access-Control-Allow-Origin: [*|origin]"
 */
void main() {
  String url = "test.txt";  
  HttpRequest request = new HttpRequest();
  request.open("GET", url, async : true);
  request.onLoadEnd.listen((ProgressEvent e) => onSuccess(e, request));
  request.send();
}

There is a request to unify HttpRequest from dart:html and HttpClient from dart:io, see http://code.google.com/p/dart/issues/detail?id=2677

Upvotes: 4

Chris Buckett
Chris Buckett

Reputation: 14378

dart:html is a client side library, whereas dart:io is a server side library. dart:html makes use of features of the browser, but dart:io makes use of features that are restricted by browser security (such as file system access an so-on).

It may be that the time comes that you can use dart:html on the server, with a "mocked" browser, which could be useful for unit testing and the like, but you can't do that yet.

Upvotes: 11

Related Questions