what's the different between full path and relative path in dart

雨燕双飞 提交于 2021-02-07 14:24:12

问题


I develop a flutter app, define serveral models in 'model' package.

Then I declare a class Example in 'model' for example.

model/example.dart

class Example {
  @override
  String toString() {
    return 'class example';
  }
}

test_a.dart

import 'package:example/model/example.dart'

Example testA() {
  return Example()
}

test.dart

import 'model/example.dart'
import 'test_a.dart'

test() {
  Example example = testA();
  if (example is Example) {
    print('this class is Example');
  } else {
    print('$example');
  }
}

I will get output class example🌚

If I change from import 'model/example.dart' to import 'package:example/model/example.dart' in test.dart, then I will get the output this class is Example.

So I'm confused what is different between the full path and relative path in dart.


回答1:


package imports

'package:... imports work from everywhere to import files from lib/*.

relative imports

Relative imports are always relative to the importing file. If lib/model/test.dart imports 'example.dart', it imports lib/model/example.dart.

If you want to import test/model_tests/fixture.dart from any file within test/*, you can only use relative imports because package imports always assume lib/.

This also applies for all other non-lib/ top-level directories like drive_test/, example/, tool/, ...

lib/main.dart

There is currently a known issue with entry-point files in lib/* like lib/main.dart in Flutter. https://github.com/dart-lang/sdk/issues/33076

Dart always assumed entry-point files to be in other top-level directories then lib/ (like bin/, web/, tool/, example/, ...). Flutter broke this assumption. Therefore you currently must not use relative imports in entry-point files inside lib/

See also

  • How to reference another file in Dart?


来源:https://stackoverflow.com/questions/50732897/whats-the-different-between-full-path-and-relative-path-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!