Tino
Tino

Reputation: 203

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

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.

Upvotes: 5

Views: 7041

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657937

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

Upvotes: 10

Related Questions