【问题标题】:How do I import dart:html & dart:io in the same class?如何在同一个类中导入 dart:html 和 dart:io?
【发布时间】:2012-04-15 17:53:44
【问题描述】:

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

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

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

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

...这是预期的。

所以我的问题是:如何在同一个类中导入 dart:html 和 dart: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();
}

【问题讨论】:

    标签: dart


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      简短的回答,你不能。正如 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和来自dart:io的HttpClient,见http://code.google.com/p/dart/issues/detail?id=2677

      【讨论】:

        猜你喜欢
        • 2021-08-16
        • 2012-11-04
        • 2014-04-02
        • 2020-01-26
        • 2021-01-28
        • 2013-01-27
        • 1970-01-01
        • 2015-05-23
        • 2013-12-22
        相关资源
        最近更新 更多