5

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.

Tino
  • 183
  • 3
  • 9
  • Can you please change the location (paths) of the files like `test_a.dart` so that it's clear where they ares stored related to `pubspec.yaml`? `test_a.dart` sounds like it might be in `test/test_a.dart` but I guess it's `lib/test_a.dart`, it's just confusing. – Günter Zöchbauer Jun 07 '18 at 06:42

1 Answers1

10

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

Luan Nico
  • 5,376
  • 2
  • 30
  • 60
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    I needed `import 'package:packageNameFromPubspec/myFileInLib.dart';` If you change your package name in `pubspec.yaml` run `pub get` to propagate the change. – Paul Parker Jan 04 '20 at 07:34