Use object setters dynamically with dart

Viewed 42

Objective

Create a method that sets value to the object created above.

This method could be used like below.

setValueToUser(userPropertyName, value);

Given

  • A mutable model made with freezed.
import 'package:freezed_annotation/freezed_annotation.dart';

part 'user.freezed.dart';
part 'user.g.dart';

@unfreezed
class User with _$User {
  factory User({
    required int id,
    required String email,
    required String password,
    required DateTime birthday,
  }) = _User;

  factory User.fromJson(Map<String, dynamic> json) =>
      _$UserFromJson(json);
}

What I tried

switch-case statement

First, I made something like this, but this ends up being very tedious as an actual user model has 109 property members :(

User setValueToUser(String propertyName, dynamic value){
   final user = User();
   switch (propertyName) {
      case 'id': 
         user.id = value as int;
         break
      case 'email': 
         user.email = value as String;
         break
      case 'password': 
         user.password = value as String;
         break
      case 'birthday': 
         user.birthday = value as DateTime;
         break
   }
   return user;
}

Map

Then, I created a map, but dart requires all fields of a map to be initialized when the map variable initializes, so failed achieve the goal.

User setValueToUser(String propertyName, dynamic value) {
   final user = User();
   final userDictionary =  <String, dynamic>{
      'id': user.id = value as int,
      'email': user.email = value as String,      
      'password': user.password = value as String,
      'birthday': user.birthday = value as DateTime,
   };
   userDictionary[propertyName];   // I intend to set value to ONLY one specific property at a time. Apparently, this line means nothing to dart :(
   return user;
}

Conclusion

I know setting a property name with string looks very ridiculous. I do want to avoid using string if possible, so comments and answers regarding this is very much welcomed. (But setting enum for all properties of the class would be tedious, I think)

0 Answers
Related