如何导入dart:html&飞镖:io在同一个班级?

时间:2012-04-15 17:53:45

标签: dart

下面的代码“看起来正确”,它编译但不运行,失败了控制台消息:

  

无法加载Dart脚本dart:io
  无法加载资源

如果我注释掉了#import('dart:io');,我相信错了,我收到了编译错误,但它启动了,直到我按下按钮,我才收到运行时错误:

  

内部错误:'http://127.0.0.1:3030/home/david/dart/samples/htmlIO/htmlIO.dart':错误:第13行pos 26:未加载类型'HttpClient'      var connection = new HttpClient()。get('www.google.com',80,'/');

......这是预期的。

所以我的问题是:如何导入dart:html&飞镖:io在同一个班级?

#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();
}

2 个答案:

答案 0 :(得分:10)

dart:html是客户端库,而dart:io是服务器端库。 dart:html使用浏览器的功能,但dart:io使用受浏览器安全性限制的功能(例如文件系统访问等)。

可能是时候你可以在服务器上使用dart:html,使用“模拟”浏览器,这可能对单元测试等有用,但你还不能这样做。

答案 1 :(得分:4)

简短的回答,你不能。正如Chris提到的那样,dart:io库仅适用于服务器库。

我发现您正在尝试连接HTML应用中的HTTP服务。你应该看看HttpRequest库。以下是示例的链接: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();
}

有一个请求从dart:html统一HttpRequest:html和HttpClient来自dart:io,请参阅http://code.google.com/p/dart/issues/detail?id=2677