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

335

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.

Share:
335
proninyaroslav
Author by

proninyaroslav

Updated on December 29, 2022

Comments

  • proninyaroslav
    proninyaroslav over 1 year

    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.

  • proninyaroslav
    proninyaroslav almost 3 years
    Runtime checks are not suitable because I need to build a project with different dependencies. For example, in one version I need Flutter, and in the other I don't.
  • Alexander Belokon
    Alexander Belokon almost 3 years
    I see but this is currently not possible for custom defined properties. What you can do is move the common code base into a plugin and split the rest into two projects.