firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.57k stars 3.94k forks source link

🐛 [cloud_firestore_odm] Cannot update with a List of objects #8233

Closed ThangVuNguyenViet closed 2 years ago

ThangVuNguyenViet commented 2 years ago

Bug report

Describe the bug When performs an update with the parameter is a list of objects, the "Unhandled Exception: Invalid argument: Instance of 'ClassName'" is shown

Steps to reproduce

Steps to reproduce the behavior:

  1. Create a model which holds a list of objects and its ref
  2. Generate code
  3. Perform and update with the ref, passing the list of instances of objects

Expected behavior

Be able to update, which results in an array of Map in the firestore document

Sample project

void main() async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  final docId = FirebaseAuth.instance.currentUser?.uid;
  userRef.doc(docId).update(as: [const A(text: 'text')]);
}

@JsonSerializable()
class User {
  final List<A> aList;

  User({
    this.aList = const [],
  });
}

@JsonSerializable()
class A {
  final String text;

  const A({required this.text});

  factory A.fromJson(Map<String, dynamic> json) => _$AFromJson(json);
  Map<String, dynamic> toJson() => _$AToJson(this);
}

@Collection<User>('users')
final userRef = UserCollectionReference();

Running the code above shows

#7      FirestoreMessageCodec.writeValue
package:cloud_firestore_platform_interface/…/utils/firestore_message_codec.dart:114
#8      StandardMessageCodec.writeValue.<anonymous closure>
package:flutter/…/services/message_codecs.dart:423
#9      _LinkedHashMapMixin.forEach (dart:collection-patch[/compact_hash.dart:539:8]())
#10     StandardMessageCodec.writeValue
package:flutter/…/services/message_codecs.dart:421
#11     FirestoreMessageCodec.writeValue
package:cloud_firestore_platform_interface/…/utils/firestore_message_codec.dart:114
#12     StandardMethodCodec.encodeMethodCall
package:flutter/…/services/message_codecs.dart:561
#13     MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:169
#14     MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:350
#15     MethodChannelDocumentReference.update
package:cloud_firestore_platform_interface/…/method_channel/method_channel_document_reference.dart:51
#16     _JsonDocumentReference.update
package:cloud_firestore/src/document_reference.dart:175
#17     _WithConverterDocumentReference.update
package:cloud_firestore/src/document_reference.dart:286
#18     _$UserDocumentReference.update
package:expense_manager/models/user.g.dart:195
#19     main
package:expense_manager/main.dart:16
<asynchronous suspension>

Note that the code above has been simplified, so the line number and the model folder does not match.


Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand ``` [✓] Flutter (Channel stable, 2.10.1, on macOS 12.2.1 21D62 darwin-arm, locale en-VN) [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0) [✓] Xcode - develop for iOS and macOS (Xcode 13.2.1) [✓] Chrome - develop for the web [✓] Android Studio (version 2020.3) [✓] VS Code (version 1.65.0) ```

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand ``` Dart SDK 2.16.1 Flutter SDK 2.10.1 expense_manager 1.0.0+1 dependencies: - cloud_firestore 3.1.10 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta] - cloud_firestore_odm 1.0.0-dev.10 [cloud_firestore flutter meta] - contacts_service 0.6.3 [flutter collection quiver] - cupertino_icons 1.0.4 - datetime_picker_formfield 2.0.0 [flutter intl] - firebase_auth 3.3.9 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta] - firebase_core 1.13.1 [firebase_core_platform_interface firebase_core_web flutter meta] - flutter 0.0.0 [characters collection material_color_utilities meta typed_data vector_math sky_engine] - google_fonts 2.3.1 [flutter http path_provider crypto] - json_annotation 4.4.0 [meta] - local_auth 1.1.11 [flutter flutter_plugin_android_lifecycle intl platform] - permission_handler 9.2.0 [flutter meta permission_handler_android permission_handler_apple permission_handler_windows permission_handler_platform_interface] - pin_code_fields 7.3.0 [flutter] dev dependencies: - build_runner 2.1.7 [args async analyzer build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style frontend_server_client glob graphs http_multi_server io js logging meta mime package_config path pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml] - cloud_firestore_odm_generator 1.0.0-dev.10 [analyzer build build_config cloud_firestore_odm collection json_annotation meta recase source_gen] - flutter_lints 1.0.4 [lints] - flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher material_color_utilities meta source_span stream_channel string_scanner term_glyph typed_data] - json_serializable 6.1.4 [analyzer async build build_config collection json_annotation meta path pub_semver pubspec_parse source_gen source_helper] transitive dependencies: - _fe_analyzer_shared 31.0.0 [meta] - analyzer 2.8.0 [_fe_analyzer_shared cli_util collection convert crypto glob meta package_config path pub_semver source_span watcher yaml] - args 2.3.0 - async 2.8.2 [collection meta] - boolean_selector 2.1.0 [source_span string_scanner] - build 2.2.1 [analyzer async convert crypto glob logging meta path] - build_config 1.0.0 [checked_yaml json_annotation path pubspec_parse yaml] - build_daemon 3.0.1 [built_collection built_value http_multi_server logging path pool shelf shelf_web_socket stream_transform watcher web_socket_channel] - build_resolvers 2.0.6 [analyzer async build crypto graphs logging path package_config pool pub_semver stream_transform yaml] - build_runner_core 7.2.3 [async build build_config build_resolvers collection convert crypto glob graphs json_annotation logging meta path package_config pool timing watcher yaml] - built_collection 5.1.1 - built_value 8.1.4 [built_collection collection fixnum meta] - characters 1.2.0 - charcode 1.3.1 - checked_yaml 2.0.1 [json_annotation source_span yaml] - cli_util 0.3.5 [meta path] - clock 1.1.0 - cloud_firestore_platform_interface 5.5.1 [collection firebase_core flutter meta plugin_platform_interface] - cloud_firestore_web 2.6.10 [cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js] - code_builder 4.1.0 [built_collection built_value collection matcher meta] - collection 1.15.0 - convert 3.0.1 [typed_data] - crypto 3.0.1 [collection typed_data] - dart_style 2.2.1 [analyzer args path pub_semver source_span] - fake_async 1.2.0 [clock collection] - ffi 1.1.2 - file 6.1.2 [meta path] - firebase_auth_platform_interface 6.2.1 [firebase_core flutter meta plugin_platform_interface] - firebase_auth_web 3.3.9 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser intl js meta] - firebase_core_platform_interface 4.2.5 [collection flutter meta plugin_platform_interface] - firebase_core_web 1.6.1 [firebase_core_platform_interface flutter flutter_web_plugins js meta] - fixnum 1.0.0 - flutter_plugin_android_lifecycle 2.0.5 [flutter] - flutter_web_plugins 0.0.0 [flutter js characters collection material_color_utilities meta typed_data vector_math] - frontend_server_client 2.1.2 [async path] - glob 2.0.2 [async collection file path string_scanner] - graphs 2.1.0 [collection] - http 0.13.4 [async http_parser meta path] - http_multi_server 3.2.0 [async] - http_parser 4.0.0 [charcode collection source_span string_scanner typed_data] - intl 0.17.0 [clock path] - io 1.0.3 [meta path string_scanner] - js 0.6.3 - lints 1.0.1 - logging 1.0.2 - matcher 0.12.11 [stack_trace] - material_color_utilities 0.1.3 - meta 1.7.0 - mime 1.0.1 - package_config 2.0.2 [path] - path 1.8.0 - path_provider 2.0.9 [flutter path_provider_android path_provider_ios path_provider_linux path_provider_macos path_provider_platform_interface path_provider_windows] - path_provider_android 2.0.12 [flutter path_provider_platform_interface] - path_provider_ios 2.0.8 [flutter path_provider_platform_interface] - path_provider_linux 2.1.5 [ffi flutter path path_provider_platform_interface xdg_directories] - path_provider_macos 2.0.5 [flutter path_provider_platform_interface] - path_provider_platform_interface 2.0.3 [flutter platform plugin_platform_interface] - path_provider_windows 2.0.5 [ffi flutter path path_provider_platform_interface win32] - permission_handler_android 9.0.2+1 [flutter permission_handler_platform_interface] - permission_handler_apple 9.0.3 [flutter permission_handler_platform_interface] - permission_handler_platform_interface 3.7.0 [flutter meta plugin_platform_interface] - permission_handler_windows 0.1.0 [flutter permission_handler_platform_interface] - platform 3.1.0 - plugin_platform_interface 2.1.2 [meta] - pool 1.5.0 [async stack_trace] - process 4.2.4 [file path platform] - pub_semver 2.1.0 [collection meta] - pubspec_parse 1.2.0 [checked_yaml collection json_annotation pub_semver yaml] - quiver 3.0.1+1 [matcher] - recase 4.0.0 - shelf 1.2.0 [async collection http_parser path stack_trace stream_channel] - shelf_web_socket 1.0.1 [shelf stream_channel web_socket_channel] - sky_engine 0.0.99 - source_gen 1.2.1 [analyzer async build dart_style glob meta path source_span yaml] - source_helper 1.3.1 [analyzer collection source_gen] - source_span 1.8.1 [collection path term_glyph] - stack_trace 1.10.0 [path] - stream_channel 2.1.0 [async] - stream_transform 2.0.0 - string_scanner 1.1.0 [charcode source_span] - term_glyph 1.2.0 - test_api 0.4.8 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph matcher] - timing 1.0.0 [json_annotation] - typed_data 1.3.0 [collection] - vector_math 2.1.1 - watcher 1.0.1 [async path] - web_socket_channel 2.1.0 [async crypto stream_channel] - win32 2.4.1 [ffi] - xdg_directories 0.2.0+1 [meta path process] - yaml 3.1.0 [collection source_span string_scanner] ```

darshankawar commented 2 years ago

@ThangVuNguyenViet Can you provide missing _$AToJson(this) and @Collection<User>('users') final userRef = UserCollectionReference(); details so that we can use it to run and verify ?

ThangVuNguyenViet commented 2 years ago
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'user.dart';

// **************************************************************************
// CollectionGenerator
// **************************************************************************

// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides

class _Sentinel {
  const _Sentinel();
}

const _sentinel = _Sentinel();

/// A collection reference object can be used for adding documents,
/// getting document references, and querying for documents
/// (using the methods inherited from Query).
abstract class UserCollectionReference
    implements UserQuery, FirestoreCollectionReference<UserQuerySnapshot> {
  factory UserCollectionReference([
    FirebaseFirestore? firestore,
  ]) = _$UserCollectionReference;

  static User fromFirestore(
    DocumentSnapshot<Map<String, Object?>> snapshot,
    SnapshotOptions? options,
  ) {
    return _$UserFromJson(snapshot.data()!);
  }

  static Map<String, Object?> toFirestore(
    User value,
    SetOptions? options,
  ) {
    return _$UserToJson(value);
  }

  @override
  UserDocumentReference doc([String? id]);

  /// Add a new document to this collection with the specified data,
  /// assigning it a document ID automatically.
  Future<UserDocumentReference> add(User value);
}

class _$UserCollectionReference extends _$UserQuery
    implements UserCollectionReference {
  factory _$UserCollectionReference([FirebaseFirestore? firestore]) {
    firestore ??= FirebaseFirestore.instance;

    return _$UserCollectionReference._(
      firestore.collection('users').withConverter(
            fromFirestore: UserCollectionReference.fromFirestore,
            toFirestore: UserCollectionReference.toFirestore,
          ),
    );
  }

  _$UserCollectionReference._(
    CollectionReference<User> reference,
  ) : super(reference, reference);

  String get path => reference.path;

  @override
  CollectionReference<User> get reference =>
      super.reference as CollectionReference<User>;

  @override
  UserDocumentReference doc([String? id]) {
    return UserDocumentReference(
      reference.doc(id),
    );
  }

  @override
  Future<UserDocumentReference> add(User value) {
    return reference.add(value).then((ref) => UserDocumentReference(ref));
  }

  @override
  bool operator ==(Object other) {
    return other is _$UserCollectionReference &&
        other.runtimeType == runtimeType &&
        other.reference == reference;
  }

  @override
  int get hashCode => Object.hash(runtimeType, reference);
}

abstract class UserDocumentReference
    extends FirestoreDocumentReference<UserDocumentSnapshot> {
  factory UserDocumentReference(DocumentReference<User> reference) =
      _$UserDocumentReference;

  DocumentReference<User> get reference;

  /// A reference to the [UserCollectionReference] containing this document.
  UserCollectionReference get parent {
    return _$UserCollectionReference(reference.firestore);
  }

  @override
  Stream<UserDocumentSnapshot> snapshots();

  @override
  Future<UserDocumentSnapshot> get([GetOptions? options]);

  @override
  Future<void> delete();

  Future<void> update({
    List<A> aList,
  });

  Future<void> set(User value);
}

class _$UserDocumentReference
    extends FirestoreDocumentReference<UserDocumentSnapshot>
    implements UserDocumentReference {
  _$UserDocumentReference(this.reference);

  @override
  final DocumentReference<User> reference;

  /// A reference to the [UserCollectionReference] containing this document.
  UserCollectionReference get parent {
    return _$UserCollectionReference(reference.firestore);
  }

  @override
  Stream<UserDocumentSnapshot> snapshots() {
    return reference.snapshots().map((snapshot) {
      return UserDocumentSnapshot._(
        snapshot,
        snapshot.data(),
      );
    });
  }

  @override
  Future<UserDocumentSnapshot> get([GetOptions? options]) {
    return reference.get(options).then((snapshot) {
      return UserDocumentSnapshot._(
        snapshot,
        snapshot.data(),
      );
    });
  }

  @override
  Future<void> delete() {
    return reference.delete();
  }

  Future<void> update({
    Object? aList = _sentinel,
  }) async {
    final json = {
      if (aList != _sentinel) "aList": aList as List<A>,
    };

    return reference.update(json);
  }

  Future<void> set(User value) {
    return reference.set(value);
  }

  @override
  bool operator ==(Object other) {
    return other is UserDocumentReference &&
        other.runtimeType == runtimeType &&
        other.parent == parent &&
        other.id == id;
  }

  @override
  int get hashCode => Object.hash(runtimeType, parent, id);
}

class UserDocumentSnapshot extends FirestoreDocumentSnapshot {
  UserDocumentSnapshot._(
    this.snapshot,
    this.data,
  );

  @override
  final DocumentSnapshot<User> snapshot;

  @override
  UserDocumentReference get reference {
    return UserDocumentReference(
      snapshot.reference,
    );
  }

  @override
  final User? data;
}

abstract class UserQuery implements QueryReference<UserQuerySnapshot> {
  @override
  UserQuery limit(int limit);

  @override
  UserQuery limitToLast(int limit);

  UserQuery whereAList({
    List<A>? isEqualTo,
    List<A>? isNotEqualTo,
    List<A>? isLessThan,
    List<A>? isLessThanOrEqualTo,
    List<A>? isGreaterThan,
    List<A>? isGreaterThanOrEqualTo,
    bool? isNull,
    List<A>? arrayContainsAny,
  });

  UserQuery orderByAList({
    bool descending = false,
    List<A> startAt,
    List<A> startAfter,
    List<A> endAt,
    List<A> endBefore,
    UserDocumentSnapshot? startAtDocument,
    UserDocumentSnapshot? endAtDocument,
    UserDocumentSnapshot? endBeforeDocument,
    UserDocumentSnapshot? startAfterDocument,
  });
}

class _$UserQuery extends QueryReference<UserQuerySnapshot>
    implements UserQuery {
  _$UserQuery(
    this.reference,
    this._collection,
  );

  final CollectionReference<Object?> _collection;

  @override
  final Query<User> reference;

  UserQuerySnapshot _decodeSnapshot(
    QuerySnapshot<User> snapshot,
  ) {
    final docs = snapshot.docs.map((e) {
      return UserQueryDocumentSnapshot._(e, e.data());
    }).toList();

    final docChanges = snapshot.docChanges.map((change) {
      return FirestoreDocumentChange<UserDocumentSnapshot>(
        type: change.type,
        oldIndex: change.oldIndex,
        newIndex: change.newIndex,
        doc: UserDocumentSnapshot._(change.doc, change.doc.data()),
      );
    }).toList();

    return UserQuerySnapshot._(
      snapshot,
      docs,
      docChanges,
    );
  }

  @override
  Stream<UserQuerySnapshot> snapshots([SnapshotOptions? options]) {
    return reference.snapshots().map(_decodeSnapshot);
  }

  @override
  Future<UserQuerySnapshot> get([GetOptions? options]) {
    return reference.get(options).then(_decodeSnapshot);
  }

  @override
  UserQuery limit(int limit) {
    return _$UserQuery(
      reference.limit(limit),
      _collection,
    );
  }

  @override
  UserQuery limitToLast(int limit) {
    return _$UserQuery(
      reference.limitToLast(limit),
      _collection,
    );
  }

  UserQuery whereAList({
    List<A>? isEqualTo,
    List<A>? isNotEqualTo,
    List<A>? isLessThan,
    List<A>? isLessThanOrEqualTo,
    List<A>? isGreaterThan,
    List<A>? isGreaterThanOrEqualTo,
    bool? isNull,
    List<A>? arrayContainsAny,
  }) {
    return _$UserQuery(
      reference.where(
        'aList',
        isEqualTo: isEqualTo,
        isNotEqualTo: isNotEqualTo,
        isLessThan: isLessThan,
        isLessThanOrEqualTo: isLessThanOrEqualTo,
        isGreaterThan: isGreaterThan,
        isGreaterThanOrEqualTo: isGreaterThanOrEqualTo,
        isNull: isNull,
        arrayContainsAny: arrayContainsAny,
      ),
      _collection,
    );
  }

  UserQuery orderByAList({
    bool descending = false,
    Object? startAt = _sentinel,
    Object? startAfter = _sentinel,
    Object? endAt = _sentinel,
    Object? endBefore = _sentinel,
    UserDocumentSnapshot? startAtDocument,
    UserDocumentSnapshot? endAtDocument,
    UserDocumentSnapshot? endBeforeDocument,
    UserDocumentSnapshot? startAfterDocument,
  }) {
    var query = reference.orderBy('aList', descending: descending);

    if (startAtDocument != null) {
      query = query.startAtDocument(startAtDocument.snapshot);
    }
    if (startAfterDocument != null) {
      query = query.startAfterDocument(startAfterDocument.snapshot);
    }
    if (endAtDocument != null) {
      query = query.endAtDocument(endAtDocument.snapshot);
    }
    if (endBeforeDocument != null) {
      query = query.endBeforeDocument(endBeforeDocument.snapshot);
    }

    if (startAt != _sentinel) {
      query = query.startAt([startAt]);
    }
    if (startAfter != _sentinel) {
      query = query.startAfter([startAfter]);
    }
    if (endAt != _sentinel) {
      query = query.endAt([endAt]);
    }
    if (endBefore != _sentinel) {
      query = query.endBefore([endBefore]);
    }

    return _$UserQuery(query, _collection);
  }

  @override
  bool operator ==(Object other) {
    return other is _$UserQuery &&
        other.runtimeType == runtimeType &&
        other.reference == reference;
  }

  @override
  int get hashCode => Object.hash(runtimeType, reference);
}

class UserQuerySnapshot
    extends FirestoreQuerySnapshot<UserQueryDocumentSnapshot> {
  UserQuerySnapshot._(
    this.snapshot,
    this.docs,
    this.docChanges,
  );

  final QuerySnapshot<User> snapshot;

  @override
  final List<UserQueryDocumentSnapshot> docs;

  @override
  final List<FirestoreDocumentChange<UserDocumentSnapshot>> docChanges;
}

class UserQueryDocumentSnapshot extends FirestoreQueryDocumentSnapshot
    implements UserDocumentSnapshot {
  UserQueryDocumentSnapshot._(this.snapshot, this.data);

  @override
  final QueryDocumentSnapshot<User> snapshot;

  @override
  UserDocumentReference get reference {
    return UserDocumentReference(snapshot.reference);
  }

  @override
  final User data;
}

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

User _$UserFromJson(Map<String, dynamic> json) => User(
      aList: (json['aList'] as List<dynamic>?)
              ?.map((e) => A.fromJson(e as Map<String, dynamic>))
              .toList() ??
          const [],
    );

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'aList': instance.aList,
    };

A _$AFromJson(Map<String, dynamic> json) => A(
      text: json['text'] as String,
    );

Map<String, dynamic> _$AToJson(A instance) => <String, dynamic>{
      'text': instance.text,
    };

Here are the generated code using flutter pub run build_runner build

darshankawar commented 2 years ago

Thanks for the update.

/cc @rrousselGit

rrousselGit commented 2 years ago

Since your snippets are relying on json_serializable, you will have to set json_serializable's explicitToJson to true. Otherwise the toJson generated by json_serializable doesn't fully serialize objects, leading to this error.

See https://stackoverflow.com/questions/53458535/flutter-json-serializable-tojson-does-not-work-properly