Skip to content

Instantly share code, notes, and snippets.

@DiegoCarvalho75
Created October 14, 2022 18:10
Show Gist options
  • Save DiegoCarvalho75/4668ac6b6c5ea87173d31779a324d49e to your computer and use it in GitHub Desktop.
Save DiegoCarvalho75/4668ac6b6c5ea87173d31779a324d49e to your computer and use it in GitHub Desktop.
Factory constructor example
class Logger {
final String name;
bool mute = false;
// _cache is library-private, thanks to
// the _ in front of its name.
static final Map<String, Logger> _cache = <String, Logger>{};
factory Logger(String name) {
return _cache.putIfAbsent(name, () => Logger._internal(name));
}
factory Logger.fromJson(Map<String, Object> json) {
return Logger(json['name'].toString());
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) print(msg);
}
}
void main() {
var logger = Logger('UI');
logger.log('Button clicked');
var logMap = {'name': 'UI'};
var loggerJson = Logger.fromJson(logMap);
print (loggerJson.name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment