2013-11-01 57 views
9

导入语句中showas之间的区别是什么?导入声明中“show”和“as”有什么区别?

例如,什么是

import 'dart:convert' show JSON; 

import 'package:google_maps/google_maps.dart' as GoogleMap; 

什么时候使用show当我应该使用as之间的区别?

如果我切换到show GoogleMap所有对GoogleMap(例如GoogleMap.LatLng)对象的引用都会报告为未定义。

回答

17

asshow是两个不同的概念。

With as您正在给导入的库命名。通常这样做的目的是防止图书馆污染你的名字空间,如果它有很多全局函数的话。如果您使用as,则可以按照您在示例中所做的方式访问该库的所有功能和类:GoogleMap.LatLng

使用show(和hide),您可以选择要在应用程序中可见的特定类。为了您的例子那就是:

import 'package:google_maps/google_maps.dart' show LatLng; 

有了这个,你将能够从该库访问LatLng,但没有别的。这种相对的是:

import 'package:google_maps/google_maps.dart' hide LatLng; 

有了这个,你将能够从该库访问的一切,除了LatLng

如果你想使用多个同名的类,你需要使用as。您也可以结合这两种方法:

import 'package:google_maps/google_maps.dart' as GoogleMap show LatLng; 
3

show情况:

import 'dart:async' show Stream;

这样,你只能从dart:async导入Stream类,因此,如果您尝试使用另一个类从dart:async以外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 
} 

as情况:

import 'dart:async' as async;

这种方式导入从dart:async所有类以及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' 
} 

as如果你有一个图书馆my_library通常是用来当你导入库是相互矛盾的类,例如。镖”,它包含一个名为类和Stream你也想用Stream类从dart:async然后:

import 'dart:async'; 
import 'my_library.dart'; 

void main() { 
    Stream stream = new Stream.fromIterable([1, 2]); 
} 

这样,我们不知道这个Stream类是来自异步库或您自己的库。我们必须使用as

import 'dart:async'; 
import 'my_library.dart' as myLib; 

void main() { 
    Stream stream = new Stream.fromIterable([1, 2]); // from async 
    myLib.Stream myCustomStream = new myLib.Stream(); // from your library 
} 

对于show,我想,当我们知道我们只需要一个特定的类时使用。也可以在导入库中存在冲突的类时使用。比如说,在您自己的图书馆中,您有一个名为CustomStreamStream的课程,您也希望使用dart:async,但在这种情况下,您只需要从您自己的图书馆购买CustomStream

import 'dart:async'; 
import 'my_library.dart'; 

void main() { 
    Stream stream = new Stream.fromIterable([1, 2]); // not doable 
                // we don't know whether Stream 
                // is from async lib ir your own 
    CustomStream customStream = new CustomStream();// doable 
} 

一些解决方法:

import 'dart:async'; 
import 'my_library.dart' show CustomStream; 

void main() { 
    Stream stream = new Stream.fromIterable([1, 2]); // doable, since we only import Stream 
                // async lib 
    CustomStream customStream = new CustomStream();// doable 
} 
相关问题