0

This is a piece of external code I work with.

class Entry {
  const Entry({this.entry, @required this.entryId});

  final String entryId;
  final String entry;

  factory Entry.fromJson(Map<String, dynamic> json) {
    return Entry(entry: json['entry'], entryId: json['entryId']);
  }

  Map<String, dynamic> toMap() {
    return {'entry': entry, 'entryId': entryId};
  }
}

What is a purpose of factory there? It's not a singleton pattern usage, then what is it? The named constructor Entry.fromJson just creates an instance of Entry from json values, then what is the factory keyword meaning?

rozerro
  • 5,787
  • 9
  • 46
  • 94

2 Answers2

0

From dart manual

Factory constructors

Use the factory keyword when implementing a constructor that doesn’t always create a new instance of its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype. Another use case for factory constructors is initializing a final variable using logic that can’t be handled in the initializer list.

baliman
  • 588
  • 2
  • 8
  • 27
0

When you look at the manual, it says

Use the factory keyword when implementing a constructor that doesn’t always create a new instance of its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype. Another use case for factory constructors is initializing a final variable using logic that can’t be handled in the initializer list.

And that is exactly what you are doing. You want to have two final fields (entryId and entry) that need to be initialized in the declaration, from the constructors parameters or in the initializer list. But you want to apply some logic to the parameters to get their contents and that is only possible in the body. So you need a factory constructor, a normal constructor would not be able to do that.

nvoigt
  • 75,013
  • 26
  • 93
  • 142