Skip to content

Instantly share code, notes, and snippets.

@bobjackman
Created February 4, 2020 20:10
Show Gist options
  • Save bobjackman/ed53881133d3df697d0d1d50a7308f1c to your computer and use it in GitHub Desktop.
Save bobjackman/ed53881133d3df697d0d1d50a7308f1c to your computer and use it in GitHub Desktop.
Making fromMap Constructors Require Certain Fields
class SomeClass {
String id;
String foo;
String bar; // required
String zap; // required
SomeClass.fromMap(Map<String, dynamic> inputMap) {
this.id = inputMap['ID'];
this.foo = inputMap['Foo'];
this.bar = inputMap['Bar'];
this.zap = inputMap['Zap'];
assert(inputMap.containsKey('Bar'), "Field 'Bar' is required"); // => Failed assertion: 'inputMap.containsKey('Bar')': Field 'Bar' is required
assert(inputMap.containsKey('Zap'), "Field 'Zap' is required"); // => Failed assertion: 'inputMap.containsKey('Zap')': Field 'Zap' is required
// or //
ArgumentError.checkNotNull(inputMap['Bar'], 'Bar'); // => Unhandled exception: Invalid argument(s) (Bar): Must not be null
ArgumentError.checkNotNull(inputMap['Zap'], 'Zap'); // => Unhandled exception: Invalid argument(s) (Zap): Must not be null
}
// OR //
SomeClass.fromMap(Map<String, dynamic> inputMap) {
this.id = inputMap['ID'];
this.foo = inputMap['Foo'];
this.bar = inputMap.putIfAbsent('Bar', () => throw new ArgumentError.notNull('Bar')); // => Unhandled exception: Invalid argument(s) (Bar): Must not be null
this.zap = inputMap.putIfAbsent('Zap', () => throw new ArgumentError.notNull('Zap')); // => Unhandled exception: Invalid argument(s) (Zap): Must not be null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment