How to set a custom property for conditional import in Dart?

Viewed 469

Dart allows to use the standard library names for conditional import/export, like this:

export 'src/hw_none.dart' // Stub implementation
    if (dart.library.io) 'src/hw_io.dart' // dart:io implementation
    if (dart.library.html) 'src/hw_html.dart'; // dart:html implementation

Is it possible to define a custom property/condition? For example, pass it when compiling.

I have a project that I would like to split into two variants: Flutter variant and pure Dart variant. The choice of the variant depends at compile time, and the necessary implements of abstract classes defines at compile time.

1 Answers

Custom properties where an experimental feature in Dart 1. With Dart 2 there is no longer any support for user defined custom conditions in compile time.

Here is the discussion referencing your question.

All you can do is, switch between implementations on run time:

abstract class SomeFactory {  
  String get message;
  
  factory SomeFactory() {
    if(Platform.environment['SOME_VAR'] != null)
      return new _SomeImplementation();
    return new _SomeOtherImplementation();
  }  
}

class _SomeImplementation implements SomeFactory {  
  @override
  String get message => 'SomeImplementation';  
}

class _SomeOtherImplementation implements SomeFactory {  
  @override
  String get message => "OtherImplementation";  
}

Check this blog entry for more details.

Related