jradelmo
jradelmo

Reputation: 126

Flutter error when converting a list to a json object removing some keys

I have an error when trying to convert a list of my object to json

My error:

Unhandled Exception: type 'RxList<ItemStockEntryModel>' is not a subtype of type 'Map<dynamic, dynamic>'

My model code:

class StockEntryModel {
  final int? id;
  final double costFreight;
  final List<ItemStockEntryModel> items;

  StockEntryModel({
    this.id,
    required this.costFreight,
    required this.items,
  });

  factory StockEntryModel.fromJson(Map<String, dynamic> json) =>
      StockEntryModel(
        id: json['id'],
        costFreight: json['costFreight'],
        items: json['itemStockEntries'],
      );
  Map<String, dynamic> toJson() => {
        'id': id,
        'costFreight': costFreight,
        'itemStockEntries': items,
      };
  Map<String, dynamic> itemsToMap() => {
        'data': items,
      };
  String itemsToJson() {
    var data = {};
    final test = itemsToMap()['data'];
    final mappedItems = Map<String, dynamic>.from(test) // the error occurs here on test variable
      ..removeWhere((key, value) => value == null || key == 'product');
    print(json.encode(mappedItems));
    data['itemStockEntries'] = mappedItems;

    return json.encode(data);
  }
}

my goal is to return a json object like this

// is not complete, only example...
{
    "itemStockEntries": {
        "data": [{
            "id": 2
        }, {
            "id": 3
        }]
    }
} 

but i need remove keys if this value is null and my key product..

I saw some similar errors, but I couldn't find the one that actually causes it sorry for my bad english =(

My solution based on Loren codes. I expect to help someone also

  Map<String, dynamic> toJson() => {
        'id': id,
        'costFreight': costFreight,
        'itemStockEntries': items.map((e) => e.toJson()).toList(),
      };
  Map<String, dynamic> itemsToMap() => {
        'data': items
            .map(
              (e) => e.toJson()
                ..removeWhere(
                    (key, value) => key == 'product' || value == null),
            )
            .toList(),
      };

  Map<String, dynamic> modelToJson() {
    Map<String, dynamic> data = {};
    data['itemStockEntries'] = itemsToMap();
    data['costFreight'] = costFreight;
    print(json.encode(data));
    return data;
  }

Upvotes: 0

Views: 924

Answers (1)

Loren.A
Loren.A

Reputation: 5595

The .from method on a map needs a map to be passed into it, and you're passing in a list. So removeWhere is looking for keys and values which don't exist the way you're doing it.

So you could clear that first error getting rid of the itemsToMap function and changing the first 2 lines of your itemsToJson function to this.

var data = {'data': items}; // an actual map that you can pass in
final mappedItems = Map<String, dynamic>.from(data) // no more error here

But that's still a map with just a single key with a value of a list. So the removeWhere is not going to do anything of value here.

The List<ItemStockEntryModel> is what you need to be iterating through.

Assuming you have json serialization setup in your ItemStockEntryModel, this is closer to what you need to do. Not a complete example because I don't know what that model looks like, but it should give you the idea.

 String itemsToJson() {
    Map data = {};
    List<String> jsonList = []; // new list of json strings to pass into data map

    for (final item in items) {
      if (// item meets whatever conditions you need) {
        final jsonItem = json.encode(item);
        jsonList.add(jsonItem);
      }
    }
    data['itemStockEntries'] = {'data': jsonList};


    return json.encode(data);
  }

Upvotes: 1

Related Questions