Home > OS >  Flutter: Error: Instance of Object when I try to update user data
Flutter: Error: Instance of Object when I try to update user data

Time:03-17

I am trying to code function Update user data (name and last name) but I always get this error :

catchError: Invalid argument: Instance of 'Games'.

I think the error is because games is a list but I don't know how to deal with that

How can I solve this? Can you help me?

here is my code

User class

@JsonSerializable()
class UserData {
  final String uid;
  final String name;
  final String lastName;
  final List<Games> games;

  UserData(
      {required this.uid,
      required this.name,
      required this.lastName,
      required this.games});

  factory UserData.fromJson(Map<String, dynamic> json) =>
      _$UserDataFromJson(json);

  Map<String, dynamic> toJson() => _$UserDataToJson(this);
}

@JsonSerializable()
class Games{
  String nameG;
  String rol;

  Bands({required this.nameG, required this.rol});
  factory Games.fromJson(Map<String, dynamic> json) => _$GamesFromJson(json);

  Map<String, dynamic> toJson() => _$GamesToJson(this);
}

cubit

...

  Future<void> updateUserName({required String name, required String lastName}) async {
    emit(HomeUpdateUserDataLoadingState());
    await updateUserData(
      name: name,
      lastName:lastName
    ).then((value) {
      getUserData(userData.uid);
    });
  }

Future<void> updateUserData({
    required String name,
    required String lastName,
  }) async {
    userData = UserData(
      uid: userData.uid,
      name: name,
      lastName: lastName,
      games: userData.games,
    );

    await FirebaseFirestore.instance
        .collection('users')
        .doc(userData.uid)
        .update(userData.toJson())
        .then((value) {
      print('updated');
      emit(HomeUpdateUserDataSuccessState());
    }).catchError((error) {
      print("catchError: ${error.toString()}");
      emit(HomeUpdateUserDataErrorState(error.toString()));
    });
  }
...

CodePudding user response:

For having custom class inside another class you need to use explicitToJson: true in your target class.

@JsonSerializable(explicitToJson: true)
class UserData {
  final String uid;
  final String name;
  final String lastName;
  final List<Games> games;

  UserData(
      {required this.uid,
      required this.name,
      required this.lastName,
      required this.games});

  factory UserData.fromJson(Map<String, dynamic> json) =>
      _$UserDataFromJson(json);

  Map<String, dynamic> toJson() => _$UserDataToJson(this);
}
  • Related