Directives / Imports

When writing an application, it is sometimes necessary to add other functionalities through an import structure to your program. This behavior is also present in the Dart programming language, but the naming conventions differ and there are more varied types. Generally, the results are similar to those in other languages.

The library maps the import types from Dart into its own structure to improve handling in Kotlin. Since Kotlin and Dart are not interoperable, you need to add the required imports manually to your file. This can only be done using the DartFileSpec object, which contains all code parts located in a single .dart file.

Variants:

In the API, the given directives from the language are split into different types. The unique parts help to improve maintainability and readability of the code. The following implementations are available:

  • Dart

  • Export

  • Library

  • Part

  • Relative

Creation:

To create an Import or Directive, you don't need to learn any specific class names. The API simplifies this process by embedding it into a factory object. This factory takes some information and returns the appropriate implementation based on the provided data. The factory can be accessed over the `DirectiveFactory`.

Let's create an import for the HTML functionalities from the Dart SDK. To do this, you need to pass the IMPORT type as an argument to the factory, along with the specific part that should be imported. In our case, it is the dart:html specifier.

DirectiveFactory.create(DirectiveType.IMPORT, "dart:html")

Specifiy a prefix for an import:

Sometimes there is a case that you want to import two different libraries which have the same identifiers (path to the lib). In this case you need to specify a prefix for one or both libraries. The api provides for that `CastType` enumeration which can be used to specify which type for the cast should be used. Also a name for the cast must be provided.

DirectiveFactory.create(DirectiveType.IMPORT, "dart:http", CastType.AS, "http")

For more details on this topic, visit the official wiki

Last updated