Created
October 14, 2022 18:10
-
-
Save DiegoCarvalho75/4668ac6b6c5ea87173d31779a324d49e to your computer and use it in GitHub Desktop.
Factory constructor example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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