Flutter 条件import

使用背景与基本样式

有时候针对不同平台会使用不同dart库/dart文件,这个时候就需要根据平台条件import

import ‘default.dart’ if(condition) 'other.dart'

实际例子1

///默认导入库是’_api.dart',如果dart库是“dart.library.io”导入’_io.dart',以此类推。
import '_api.dart' if (dart.library.io) '_io.dart' if (dart.library.html) '_html.dart' as platform;

//最后的as操作
//This way you import all class from ‘***.dart’ and namespaced it with ‘platform’ keyword


class WebSocketHelper {
  /// 暴露 createWebSocketChannel函数
  static WebSocketChannel createWebSocketChannel(String address) {
    return platform.createWebSocketChannel(address);
  }
}

实际例子2

import 'dart:async' as async;

void main() {
  async.StreamController controller = new async.StreamController(); // doable
  List data = [1, 2, 3];
  Stream stream = new Stream.fromIterable(data); // not doable because you namespaced it with 'async'
}

例子3(import show)

import 'dart:async' show Stream;

void main() {
  List data = [1, 2, 3];
  Stream stream = new Stream.fromIterable(data); // doable
  StreamController controller = new StreamController(); // not doable because you only show Stream
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容