Home > Net >  Is it possible to define things globally so that they don't have to be imported? (Dart)
Is it possible to define things globally so that they don't have to be imported? (Dart)

Time:04-12

I'd like to define things like extensions to my code that are always defined in a global scope so that they don't have to be imported, and always show up on intellisense.

Is this possible?

CodePudding user response:

It doesn't seem possible to always implicitly import a set of symbols in every file.

There's no command-line option, and the language spec explicitly says that dart:core is the exception, under section 19.1 Imports:

The dart core library dart:core is implicitly imported into every dart library other than itself via an import clause of the form import ’dart:core’; unless the importing library explicitly imports dart:core. Any import of dart:core, even if restricted via show, hide, or as, preempts the automatic import.

It would be nice if there was nothing special about dart:core. However, its use is pervasive, which leads to the decision to import it automatically. [...]


However, it seems that you want extension methods to be accessible to IntelliSense in your IDE.

That is handled by the language server, which is part of the Dart SDK. There's an open issue for extension method auto-completion on the Dart SDK bug tracker: https://github.com/dart-lang/sdk/issues/38894.

A temporary workaround (by GitHub user Afur) is to create a library that would export all extensions in your project, with a special symbol that helps you automatically import that file.

For example, you'd create a file extensions.dart with the following contents:

export 'string_extension.dart';
export 'list_extension.dart';

abstract class Extensions {}

Then, in your code, you'd start typing Extensions, your IDE will suggest importing extensions.dart and voilà, your extensions are in scope.

  •  Tags:  
  • dart
  • Related