GraphQL Response Parsing Flutter Best Practices

Viewed 195

I'd like to know what the best practices are to handle GraphQL responses with flutter. As of now, I have a user model that looks like the following:

class User {
  String id;
  String email;
  String fullName;
  DateTime birthDate;
  int weight;
  int height;
  String country;
  String? trainingGoal;
  int? trainingFrequency;
  
  User({required this.id, required this.fullName, required this.email, required this.birthDate, required this.weight, required this.height, required this.country, this.trainingFrequency, this.trainingGoal});

  factory User.fromJson(Map<String, dynamic> json) => User(
    id: json["_id"],
    email: json["email"],
    fullName: json["fullName"],
    birthDate: DateTime.parse(json["birthDate"]),
    weight: json["weight"],
    height: json["height"],
    country: json["country"],
  );

}

I also have a userservice that looks like this:

class UserService {
  User? _cachedUser;
  
  void setCachedUser(User? user) {
    _cachedUser = user;
  }

  User? getCachedUser() {
    return _cachedUser;
  }

}

When I make a GraphQL mutation I get a response with the fields I modified. Should I try to merge the two classes above and then try checking whether json["field"] is null and if it is, set it to the cachedUsers value when parsing fromJson? Or is there a better way of doing this?

Edit: I'd like to have some kind of dynamic json parsing.

0 Answers
Related