Advertisement
narimetisaigopi

factory model in dart

Jan 22nd, 2023
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. void main(List<String> arguments) {
  2. // UserModel userModel = UserModel.fromJSON({"name": "sai", "uid": 123});
  3. UserModel saiModel = UserModel.fromFactory({"name": "sai", "id": 123});
  4. print(saiModel.name);
  5. }
  6.  
  7. // facotry => design pattern
  8.  
  9. /**
  10. * A factory in Dart is a method or function that returns an instance or object of a class.
  11. * It can be used as an alternative to the regular constructor, allowing for more flexibility in how objects are created.
  12. * A factory method can return an existing instance, create a new instance with specific arguments, or return a subtype of the class.
  13. * To define a factory in Dart, you use the "factory" keyword before the method name and return an object of the class' type.
  14. */
  15.  
  16. class UserModel {
  17. late String name;
  18. late int uid;
  19.  
  20. UserModel({required this.name, required this.uid});
  21.  
  22. UserModel.fromJSON(Map map) {
  23. name = map['name'];
  24. uid = map['uid'];
  25. }
  26.  
  27. factory UserModel.fromFactory(Map map) {
  28. return UserModel(name: map['name'], uid: map['id']);
  29. }
  30. }
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement