Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void main(List<String> arguments) {
- // UserModel userModel = UserModel.fromJSON({"name": "sai", "uid": 123});
- UserModel saiModel = UserModel.fromFactory({"name": "sai", "id": 123});
- print(saiModel.name);
- }
- // facotry => design pattern
- /**
- * A factory in Dart is a method or function that returns an instance or object of a class.
- * It can be used as an alternative to the regular constructor, allowing for more flexibility in how objects are created.
- * A factory method can return an existing instance, create a new instance with specific arguments, or return a subtype of the class.
- * To define a factory in Dart, you use the "factory" keyword before the method name and return an object of the class' type.
- */
- class UserModel {
- late String name;
- late int uid;
- UserModel({required this.name, required this.uid});
- UserModel.fromJSON(Map map) {
- name = map['name'];
- uid = map['uid'];
- }
- factory UserModel.fromFactory(Map map) {
- return UserModel(name: map['name'], uid: map['id']);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement