safe_config icon indicating copy to clipboard operation
safe_config copied to clipboard

Cannot decode() non-map values

Open bobjackman opened this issue 4 years ago • 0 comments

When using decode() to decode custom types, the class can't be instantiated.

Example:

import 'dart:io';

class Foo {
  static final Foo one = Foo._('one');
  static final Foo two = Foo._('two');
  static final Foo three = Foo._('three');
  
  final String name;
  
  Foo._(this.name);
}

class FooConfiguration implements Foo {
  Foo _delegate;
  
  FooConfiguration.fromFile(File file)                : super.fromFile(file);
  FooConfiguration.fromString(String yaml)            : super.fromString(yaml);
  FooConfiguration.fromMap(Map<dynamic, dynamic> yaml): super.fromMap(yaml);
  
  @override
  void decode(dynamic name) {
    name = name.toString().toLowerCase();
    
    if      (name == 'one'  ) _delegate = Foo.one;
    else if (name == 'two'  ) _delegate = Foo.two;
    else if (name == 'three') _delegate = Foo.three;
  }
  
  @override
  List<String> validate() {
    var errors = <String>[];
    if (this._delegate == null) {
      errors.add("Invalid value for `foo`. Must be one of one|two|three");
    }

    return errors;
  }
  
  String get name => _delegate.name;
}

void main() {
  // ======== Create File
  var fileContents = 'two';
  var filePath     = '/path/to/example.yaml';
  var file         = new File(filePath)..createSync()..writeAsStringSync(fileContents, flush: true);
  
  // ======== Load File
  var foo = new FooConfiguration.fromFile(filePath);
  // !!!!!!!!!!!!!!!!!!!!!!!!!
  // type 'String' is not a subtype of type 'Map<dynamic, dynamic>' in type cast
  // !!!!!!!!!!!!!!!!!!!!!!!!!
}

This error is coming from /lib/src/configuration.dart:19 which is both assuming and requiring that the contents of the file be a yaml object rather than any other valid yaml datatype.

There's a PR to fix this incoming...

bobjackman avatar Jan 21 '21 21:01 bobjackman