I have a flutter model that contains a map of type <String, Object>, and I would like to know how it should be passed in the fromJson() function, or if the way I have it is the correct way.
EDIT: I would also like to know the form for a data of type List.
CodePudding user response:
Try making it simplified and clean. Here is an example.
factory CartModel.fromJson(Map<String, dynamic> json) {
return CartModel(
productName: json['productName'],
description: json['description'],
price: json['price'],
productId: json['productId'],
rating: json['rating'],
time: json['time'],
category: json['category'],
imageUrl: json['imgUrl'],
type: json['type'],
quantity: json['quantity'],
totalPrice: json['totalPrice'],
addonList: json['addonList'],
);
}
CodePudding user response:
Function to convert Json
to Model
static Future<List<ListModel>> getList() async {
final String response = await rootBundle.loadString('assets/examle.json');
final jsonStr = await json.decode(response);
List<ListModel> list = json.decode(jsonStr);
return list;
}
Model
import 'dart:convert';
import 'package:flutter/services.dart';
class ListModel {
ListModel({
this.id,
this.name,
});
int? id;
String? name;
factory ListModel.fromRawJson(String str) =>
ListModel.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory ListModel.fromJson(Map<String, dynamic> json) => ListModel(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name == null ? null : name,
};
}
Json
[
{
"id": 1,
"name": "Anand",
},{
"id": 2,
"name": "Anand",
}
]