I'm trying to update one field in user collection witch is List of Articles and I want to add Article that list then update my save article page. lets get start with User Model

User Model


@JsonSerializable()
class AmataUser {
  String? userName;
  String? emailAddrress;
  String? uid;
  String? profileUrl;
  List<Article>? savedArticles;

  AmataUser(
      {this.emailAddrress, this.profileUrl, this.savedArticles, this.userName, this.uid});

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

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

  AmataUser copyWith(
          {String? emailAddres,
          String? password,
          String? profileUrlm,
          List<Article>? savedArticles}) =>
      AmataUser(
          profileUrl: profileUrl ?? this.profileUrl,
          emailAddrress: emailAddrress ?? this.emailAddrress,
          // password: password ?? this.password,
          savedArticles: savedArticles ?? this.savedArticles);
}

and here is my Article Models

Article Model

@JsonSerializable()
class Article {
  String? title;
  String? body;
  String? coverImageUrl;
  Article({this.body, this.coverImageUrl, this.title});

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

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

  Article copyWith({String? title, String? body, String? coverImageUrl}) {
    return Article(
      title: title??this.title,
      body: body??this.body, 
      coverImageUrl:coverImageUrl??this.coverImageUrl
    );
  }
}

with this models I try to update user savedArticles by this function from my userRepository

  Future<RawData> saveArticleToReadingList(
      {required AmataUser user, required Article article}) async {
    try {
      log('saving ${article.title} to user list');
      var doc = await _userRef.doc(user.uid).get();
      AmataUser amatauser = AmataUser.fromJson(doc.data() as Map<String, dynamic>);
      amatauser.savedArticles!.add(article);
      print(amatauser.savedArticles!.length);
      var resualt = await _userRef
          .doc(user.uid)
          .update({'savedArticles': amatauser.savedArticles});
      return RawData();
    } catch (e) {
      return RawData(operationResult: OperationResult.fail, data: e.toString());
    }
  }

the error also is ArgumentError (Invalid argument: Instance of 'Article'). I should mention that I had search before and I can't find any answer ,there was github issues like me that developer cant update list of his model but unfortunately issues was close and there wasn't any solution


Solution 1: Mansour Alhaddad

You should convert the savedArticles to List of Map as below

 var resualt = await _userRef
      .doc(user.uid)
      .update({'savedArticles': amatauser.savedArticles!.map((e) => e.toJson()).toList()});