This is the code:
class Event {
final String id;
final String name;
final String description;
final String date;
final String imgPath;
const Event({
required this.id,
required this.name,
required this.description,
required this.date,
required this.imgPath,
});
factory Event.fromJson(Map<String, dynamic> json) {
return switch (json) {
{
"id": String id,
"name": String name,
"description": String description,
"date": String date,
"imgPath": String imgPath,
} =>
Event(
id: id,
name: name,
description: description,
date: date,
imgPath: imgPath
),
_ => throw const FormatException('Couldn't fetch events'),
};
}
}
I understand the variable declaration and the const Event({..})
, however I do not quite understand factory and the shenanigans that go after return switch (json)
To my understanding we match variables from JSON with variables in this class and factory
is to prevent this class from self-initializing? Please correct me if I am wrong, this is the first time I try to create something that functions as struct in Dart.
I'll try to explain it as simple as possible. Event
is a class. You can create instances of a class by calling a constructor
. A factory
is a special kind of way to get an instance of class and will usually call a constructor
within its body. That's what's happening here. The part with
const Event
is the contructor. It is passed all the parameters for creating a new instance of an Event
.
So what's happening in the factory is so called pattern matching and is actually a relative new feature of dart. So it checks the parameter json
against the pattern
{
"id": String id,
"name": String name,
"description": String description,
"date": String date,
"imgPath": String imgPath,
}
Which means, it checks if the map json
has all the fields with keys "id", "name", "description", "date", "imgPath" and if all their values are of the String
type. And this will also store those values in local variables as named in the pattern. If the json
parameter matches this pattern it calls the constructor and uses as arguments the local variables that were matched in the pattern before and returns this instance. If it doesn't match the pattern it will throw the FormatException