0

I am trying to call this method but TempReceiptModel.fromJSON is not being called.

Future<TempReceiptModel?> getTempReceipt({
  required UserModel? user,
}) async {
  TempReceiptModel? tempReceipt;
  try {
    // print(tempReceipt.)
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? accessToken = prefs.getString('accesstoken');
    String? userID = user?.user_id;
    http.Response res = await http.get(
      Uri.parse("http://localhost:3000/getTempReceipt/$userID"),
      headers: {
        "Authorization": "Bearer $accessToken",
      },
    );
    if (res.statusCode == 200) {
      Map<String, dynamic> Receipt = jsonDecode(res.body);
      tempReceipt = TempReceiptModel.fromJson(Receipt);
    }
    return tempReceipt;
  } catch (err) {
    return tempReceipt;
  }
}

Following is the code for TempReceiptModel

class TempReceiptModel {
  final String userID;
  final double tempWeight;
  var receipt;
  final String UID;

  TempReceiptModel({
    required this.userID,
    required this.tempWeight,
    required this.receipt,
    required this.UID,
  });

  static TempReceiptModel fromJson(Map<String, dynamic> json) {
    if(json['receipt']!=null ) {
      ReceiptObject.fromJson(json['receipt']);
    }
    return TempReceiptModel(
      userID: json['userID'],
      tempWeight: json['tempWeight'] ?? 0.0,
      receipt: json['receipt'],
      UID: json['UID'],
    );
  }

The fromJSON method calls ReceiptObject.fromJSON method. Following is the code for ReceiptObject model:

class ReceiptObject {
  final double totalWeight;
  final DateTime date;
  final double netTotal;
  final double totalDiscount;
  final double? gst;
  final bool isDeleted;
  final List<ItemModel> items;

  ReceiptObject({
    required this.totalWeight,
    required this.date,
    required this.netTotal,
    required this.totalDiscount,
    required this.isDeleted,
    required this.items,
    this.gst,
  });

  static ReceiptObject fromJson(Map<String, dynamic> json) {
    return ReceiptObject(
      totalWeight: json['totalWeight'],
      date: DateTime.parse(json['date']),
      netTotal: json['netTotal'],
      totalDiscount: json['totalDiscount'],
      gst: json['gst'],
      isDeleted: json['isDeleted'],
      items: (json['items'] as List<dynamic>)
          .map((e) => ItemModel.fromJson(e))
          .toList(),
    );
  }

Following is the itemModel and itemModel.fromJSON method

class ItemModel {
 final String productID;
 final int productQuantity;
 final double grossTotal;
  bool isDeleted=false;


  ItemModel(
      {
        required this.productID,
        required this.grossTotal,
        required this.productQuantity,
        required this.isDeleted,

      });

  static ItemModel fromJson(Map<String, dynamic> json) {
    return ItemModel(
        productID :json["productID"],
        grossTotal: json["grossTotal"],
        productQuantity:json["productQuantity"],
        isDeleted:json["isDeleted"]

    );
  }


Map<String, dynamic> toJson() {
  final Map<String, dynamic> data = new Map<String, dynamic>();
  data['productID']=this.productID;
  data['productQuantity']=this.productQuantity;
  data['grossTotal']=this.grossTotal;
  data['isDeleted']=this.isDeleted;
  return data;
}

}

The models are saved in the backend as follows

const mongoose = require('mongoose');
const receiptSchema = require('./receipt_model');

var tempReceiptSchema = new mongoose.Schema({
    userID: {
        type: String,
        required: true,
        unique: true
    },
    tempWeight: {
        type: Number,
        default: 0
    },
    receipt: {
        totalWeight: {
            type: Number,
            default: 0,
            required: true
        },
        date: {
            type: Date,
            default: Date.now(),
            required: true
        },
        netTotal: {
            type: Number,
            default: 0,
            required: true
        },
        totalDiscount: {
            type: Number,
            default: 0,
            required: true
        },
        gst: {
            type: Number,
        },
        isDeleted: {
            type: Boolean,
            default: false
        },
        items: [{
            productID: {
                type: String,
                required: true
            },
            productQuantity: {
                type: Number,
                required: true
            },
            grossTotal: {
                type: Number,
                required: true
            },
            // for soft delete
            isDeleted: {
                type: Boolean,
                default: false
            }
        }]
    },
    UID: {
        type: String,
        required: true
    }
})

const receipt = mongoose.model('tempReceipt', tempReceiptSchema)
module.exports = receipt

I receive this object as the respone:

{
"tempreceipt": {
    "receipt": {
        "totalWeight": 0.30000000000000004,
        "date": "2023-04-07T17:50:44.898Z",
        "netTotal": 540,
        "totalDiscount": 0,
        "isDeleted": false,
        "items": [
            {
                "productID": "63b2d175525a0799637150bc",
                "productQuantity": 3,
                "grossTotal": 540,
                "isDeleted": false,
                "_id": "64305818becb25d9ae1a6801"
            }
        ]
    },
    "_id": "643057ffbecb25d9ae1a67f0",
    "userID": "641f4d6a11a2885a78550113",
    "tempWeight": 0,
    "UID": " D9 B9 B1 D5",
    "__v": 1
}

}

I want the TempReceiptModel to be returned from TempReceipt.fromJSON method.

  • Dear your modal name is wrog. – Jayswal Viraj Apr 07 '23 at 20:31
  • @JayswalViraj where exactly? – Huda Channa Apr 07 '23 at 20:33
  • If `TempReceiptModel.fromJson` isn't being called, then the first steps you should be doing is determining why you aren't executing that code path. Is `res.statusCode` not 200? Is `jsonDecode` throwing an exception? (Your code currently *silently swallows all errors*, which is bad.) – jamesdlin Apr 07 '23 at 20:34
  • @Huda Channa chann Dear you call wrong method name .You have this method (static ItemModel fromJson) in item model class. And you call like this method TempReceiptModel.fromJson(Receipt). So this name is wrong. How to solve this? Ans: You can go to this link and create your model class automatically. https://app.quicktype.io/ So please try it. If any problem I am available for you. Thank you.... – Jayswal Viraj Apr 07 '23 at 20:48

4 Answers4

0

Edited , based on your json output , your model should look like this:

import 'package:meta/meta.dart';
import 'dart:convert';

TemprRceiptModel temprRceiptModelFromJson(String str) => TemprRceiptModel.fromJson(json.decode(str));

String temprRceiptModelToJson(TemprRceiptModel data) => json.encode(data.toJson());

class TemprRceiptModel {
    TemprRceiptModel({
        required this.tempreceipt,
    });

    final Tempreceipt tempreceipt;

    factory TemprRceiptModel.fromJson(Map<String, dynamic> json) => TemprRceiptModel(
        tempreceipt: Tempreceipt.fromJson(json["tempreceipt"]),
    );

    Map<String, dynamic> toJson() => {
        "tempreceipt": tempreceipt.toJson(),
    };
}

class Tempreceipt {
    Tempreceipt({
        required this.receipt,
        required this.id,
        required this.userId,
        required this.tempWeight,
        required this.uid,
        required this.v,
    });

    final Receipt receipt;
    final String id;
    final String userId;
    final int tempWeight;
    final String uid;
    final int v;

    factory Tempreceipt.fromJson(Map<String, dynamic> json) => Tempreceipt(
        receipt: Receipt.fromJson(json["receipt"]),
        id: json["_id"],
        userId: json["userID"],
        tempWeight: json["tempWeight"],
        uid: json["UID"],
        v: json["__v"],
    );

    Map<String, dynamic> toJson() => {
        "receipt": receipt.toJson(),
        "_id": id,
        "userID": userId,
        "tempWeight": tempWeight,
        "UID": uid,
        "__v": v,
    };
}

class Receipt {
    Receipt({
        required this.totalWeight,
        required this.date,
        required this.netTotal,
        required this.totalDiscount,
        required this.isDeleted,
        required this.items,
    });

    final double totalWeight;
    final DateTime date;
    final int netTotal;
    final int totalDiscount;
    final bool isDeleted;
    final List<Item> items;

    factory Receipt.fromJson(Map<String, dynamic> json) => Receipt(
        totalWeight: json["totalWeight"]?.toDouble(),
        date: DateTime.parse(json["date"]),
        netTotal: json["netTotal"],
        totalDiscount: json["totalDiscount"],
        isDeleted: json["isDeleted"],
        items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "totalWeight": totalWeight,
        "date": date.toIso8601String(),
        "netTotal": netTotal,
        "totalDiscount": totalDiscount,
        "isDeleted": isDeleted,
        "items": List<dynamic>.from(items.map((x) => x.toJson())),
    };
}

class Item {
    Item({
        required this.productId,
        required this.productQuantity,
        required this.grossTotal,
        required this.isDeleted,
        required this.id,
    });

    final String productId;
    final int productQuantity;
    final int grossTotal;
    final bool isDeleted;
    final String id;

    factory Item.fromJson(Map<String, dynamic> json) => Item(
        productId: json["productID"],
        productQuantity: json["productQuantity"],
        grossTotal: json["grossTotal"],
        isDeleted: json["isDeleted"],
        id: json["_id"],
    );

    Map<String, dynamic> toJson() => {
        "productID": productId,
        "productQuantity": productQuantity,
        "grossTotal": grossTotal,
        "isDeleted": isDeleted,
        "_id": id,
    };
}

You can use quicktype.io to generate this dart model based on your json object

JosephB
  • 1
  • 1
0

Dear you call wrong method name .You have this method (static ItemModel fromJson) in item model class. And you call like this method TempReceiptModel.fromJson(Receipt). So this name is wrong.

How to solve this?

Ans: You can go to this link and create your model class automatically.

https://app.quicktype.io/

So please try it. If any problem I am available for you. Thank you....

Jayswal Viraj
  • 110
  • 1
  • 8
0

I changed my TempReceiptModel fromJSON method to this:

return TempReceiptModel(
  receipt: ReceiptObject.fromJson(json['tempreceipt']['receipt']),
  userID: json['tempreceipt']['userID'],
  tempWeight: json['tempreceipt']['tempWeight'].toDouble(),
  uid: json['tempreceipt']['UID'],
);

I did not change the rest of the code and it worked.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

So basically thats what i said in my response:

factory Tempreceipt.fromJson(Map<String, dynamic> json) => Tempreceipt(
  receipt: Receipt.fromJson(json["receipt"]),
  id: json["_id"],
  userId: json["userID"],
  tempWeight: json["tempWeight"],
  uid: json["UID"],
  v: json["__v"],
);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
JosephB
  • 1
  • 1