2

In my code, there is a place where I need to take different actions based on the input class type. So I write two lines to check an input object's class type.

debugPrint("Let me know the next action: $action");
debugPrint((action is LoadPomodorosAction).toString());

And the output is

I/flutter (24128): Let me know the next action: Instance of 'LoadPomodorosAction'
I/flutter (24128): false

What does this mean? The object 'action' is "Instance of 'LoadPomodorosAction'" and at the same time its class type is not LoadPomodorosAction .

how do I adjust my code so that I can know the class type of action? I was suspecting that maybe there is something wrong with runtimetype. But how do I get to know the runtimetype?

Lizy
  • 42
  • 1
  • 8
  • 1
    Two different classes can have the same name. Can you reproduce in https://dartpad.dartlang.org/ ? It could also be that you have relative imports in `lib/main.dart` which usually causes such issues. – Günter Zöchbauer Mar 16 '18 at 06:53
  • Yes, you are right! Splendid! I stopped using relative imports and using the absolute path instead. Now the (action is LoadPomodorsAction) would return true. Could you explain the reason of this difference to me? I am still confused about why this happens. – Lizy Mar 16 '18 at 07:07
  • 2
    Relative imports should not cause issues among files within `lib/` except `lib/main.dart` (or whatever the entrypoint file is named to start your app) – Günter Zöchbauer Mar 16 '18 at 07:09

1 Answers1

0

I've tried replicating your issue and I'm not able to reproduce it. But to explain your inquiry, here is a complete details about the difference between the relative path and absolute path when used in imports as discussed in this SO post:

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

Previously, this bug was posted in GitHub as an issue between relative and absolute path. It seems that this was resolved per this GitHub post.

MαπμQμαπkγVπ.0
  • 5,887
  • 1
  • 27
  • 65