0

I'm trying to use json_serializable:. my pubspec.yaml

dependencies:
  json_annotation: 3.1.1

dev_dependencies:
  build_runner:
  json_serializable: 3.5.1

my stream from Firestore

static Stream<DocumentSnapshot<Object>> getOrderById(String docId) {
    return database().collection('orders').doc(docId).snapshots();
  }

my factory at order.dart

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

order.g.dart

Order _$OrderFromJson(Map<String, dynamic> json) {
  return Order(
    common: json['common'] == null
        ? null
        : OrderCommon.fromJson(json['common'] as Map<String, dynamic>),
    // goes like this

when i call this method like

Order doc = Order.fromJson(snapshot.data);

throws me Expected a value of type 'Map<String, dynamic>', but got one of type '_JsonDocumentSnapshot'

But when i add another factory exactly same, just expecting parameter different.

order.dart

factory Order.fromSnapshot(DocumentSnapshot json) {
    return Order(
      common: json['common'] == null
          ? null
          : OrderCommon.fromJson(json['common'] as Map<String, dynamic>),
// goes like this but EXACTLY same with order.g.dart OrderFromJson

And call with when i call this method like

Order doc = Order.fromSnapshot(snapshot.data);

It works as expected. What's my wrong? Any comment appreciated.

Kerem
  • 840
  • 7
  • 22

1 Answers1

0

We should let Flutter know that snapshot.data is a Map<String, dynamic>:

Order doc = Order.fromJson(snapshot.data as Map<String, dynamic>);
Stefano Amorelli
  • 4,553
  • 3
  • 14
  • 30
  • 2
    Already tried that but just tried now. `Order doc = Order.fromJson(snapshot.data as Map);` `════════ Exception caught by widgets library ═══════════════════════════════════ Expected a value of type 'Map', but got one of type '_JsonDocumentSnapshot' The relevant error-causing widget was StreamBuilder> lib\screens\order_detail_screen.dart:169` – Kerem May 09 '21 at 08:39