Dart中的导入不是递归的吗?

huangapple go评论61阅读模式
英文:

Are imports in Dart not recursive?

问题

我有一个项目文件,其中包括class MyFileStream extends Stream<someList>。该文件以import 'dart:io';开始。

当我尝试在class MyFileStream内部实现函数.listen()时,我发现我还需要在同一文件中导入import 'dart:async';

问题是,dart:async已经在文件*"/dart-sdk/lib/io/io.dart"*中导入,跟在library dart.io;这一行后面。

那么,为什么我需要导入async,而它已经在io中导入了呢?这似乎与C语言不同。在Dart语言中,导入是私有的吗?这背后的想法是什么?

英文:

I have a project file which includes class MyFileStream extends Stream<someList>. The file begins with import 'dart:io';.

When I try to implement the function .listen() inside class MyFileStream I found out that I needed to import 'dart:async'; as well in the same file.

The thing is, dart:async is already imported in file "/dart-sdk/lib/io/io.dart" following the line library dart.io;.

So, why would I import async while it is already imported in io? This seems to be different than C language. Are imports private in Dart language? What is the idea behind?

答案1

得分: 3

如果A导入了B,而B导入了C,C的公共符号在B中可见,但会重新导出到A。要实现这一点,B必须使用export 'C.dart';而不仅仅是import 'C.dart';

因此,回答你的问题,导入默认情况下是递归的,但可以根据请求进行递归。这可以非常强大,还可以使用适当的show和hide操作重新导出使用的接口的子集。

一个示例是flutter_riverpod如何完全重新发布riverpod类:

export 'package:riverpod/riverpod.dart';

以及Riverpod如何谨慎地在https://github.com/rrousselGit/riverpod/blob/master/packages/riverpod/lib/riverpod.dart中导出其内部符号的一部分。

英文:

If A imports B, and B imports C, the public symbols of C are visible in B, but not re-exported to A. To do that, B would have to say export 'C.dart'; instead of just import 'C.dart';

So, to answer your question, imports are not recursive by default, but they can be, on request. This can be quite powerful, to also re-export a subset of a consumed interface using the proper show and hide operations.

An example of that is how flutter_riverpod completely re-publishes the riverpod classes:

export 'package:riverpod/riverpod.dart';

and how Riverpod carefully exports a portion of its internal symbols in https://github.com/rrousselGit/riverpod/blob/master/packages/riverpod/lib/riverpod.dart.

huangapple
  • 本文由 发表于 2023年6月11日 23:59:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定