Error To show Data Parsed Json In Flutter - json

I Have One Http Post Method Like This :
class ApiClientController extends GetxController {
Future<GetSideMenuInfoError?> GetInfoAfterLogin() async {
String? value = await storage.read(key: 'skey');
try {
final response = await dio.post(
Constant.baseUrl,
options: Options(
headers: {
"omax-apikey": "apikey",
},
),
data: {
"function": "portal_get_information",
"params": {
"portal_version": "1.0.0",
"portal_os": "linux",
"portal_os_version": "10",
"portal_browser": "chrome",
"portal_guid": "fd298776-6014-11ed-adbc-5256454165"
}
},
);
//print(response.data.toString());
GetSideMenuInfoError? responseBody = getSideMenuInfoErrorFromJson(response.data.toString());
return responseBody;
} on DioError catch (e) {
//return ;
print(e);
}
return null;
//IMPLEMENT USER LOGIN
}
}
And The Result Post Method My Json :
{
"result": 55456465,
"data": {
"reason": "session expired or not valid",
"uuid": "01dfca14-625559-11ed-aafa-0056546546"
}
}
Used This https://app.quicktype.io/ for Parsed Json To dart File Result Like This:
import 'package:meta/meta.dart';
import 'dart:convert';
GetSideMenuInfoError? getSideMenuInfoErrorFromJson(String str) => GetSideMenuInfoError?.fromJson(json.decode(str));
class GetSideMenuInfoError {
GetSideMenuInfoError({
#required this.result,
#required this.data,
});
final int? result;
final Data? data;
factory GetSideMenuInfoError.fromJson(Map<String, dynamic> json) => GetSideMenuInfoError(
result: json["result"],
data: Data.fromJson(json["data"]),
);
}
class Data {
Data({
#required this.reason,
#required this.uuid,
});
final String? reason;
final String? uuid;
factory Data.fromJson(Map<String, dynamic> json) => Data(
reason: json["reason"],
uuid: json["uuid"],
);
}
And My Question Is : How Can I Show value in Dart File Like reason or uuid In Other Class ?
My Way like This in Other Class And Not Worked:
In The Build Widget :
final apiClientController = Get.find<ApiClientController>();
apiClientController.GetInfoAfterLogin();
GetSideMenuInfoError? getSideMenuInfoError;
title: getSideMenuInfoError != null ?
Text(getSideMenuInfoError.result.toString()):Text('',),
Thank You For Helping Me...

Related

How to decode JSON to a Map<DateTime, List<Object>>

I can't figure out how to decode a JSON to a specific Map.
First of all I have a map that stores the date as the map key, and the value is a list of objects.
I also made custom methods to convert the objects to JSON.
The class model for the list of objects is:
class Task {
late int taskId;
late bool isCompleted;
late String text;
late PriorityItem priority;
Map<String, dynamic> toJson() =>
{
"id": taskId,
"isCompleted": isCompleted,
"text": text,
"priority": priority.toString(),
};
factory Task.fromJson(Map<String, dynamic> json) =>
Task(
json["isCompleted"],
taskId:json["id"],
text: json["text"],
priority: json["priority"]);
}
enum PriorityItem{
low,
medium,
high
}
The map is stored inside another class called TaskList as
static LinkedHashMap<DateTime, List<Task>> weeklyTaskMap = LinkedHashMap<DateTime, List<Task>>();
static Map<String, dynamic> toJson(LinkedHashMap<DateTime, List<Task>> taskMap) {
Map<String, dynamic> myMap = {};
taskMap.forEach((key, value) {
myMap[key.toIso8601String()] = List<dynamic>.from(value.map((x) => x.toJson()));
});
return myMap;
}
static LinkedHashMap<DateTime, List<Task>> fromJson(Map<String, dynamic> json) {
LinkedHashMap<DateTime, List<Task>> myMap = {} as LinkedHashMap<DateTime, List<Task>>;
json.forEach((key, value) {
myMap[DateTime.parse(key)] = List<Task>.from(json[value]
.map((x) => Task.fromJson(value)));
});
return myMap;
}
Encoding the map to JSON is working just fine, this would be an output after encoding the map:
{
"2022-11-14T15:38:52.879009": [
{
"id": 0,
"isCompleted": false,
"text": "how to get rid ",
"priority": "PriorityItem.medium"
},
{
"id": 1,
"isCompleted": false,
"text": "good morning and I ",
"priority": "PriorityItem.low"
}
],
"2022-11-15T00:00:00.000Z": [
{
"id": 2,
"isCompleted": false,
"text": "how to get rid of the ",
"priority": "PriorityItem.high"
}
]
}
Methods used to encode and decode:
void getMapsFromPrefs() async {
SharedPreferences getMaps = await _prefs;
Map dailyMap = TaskList.fromJson(jsonDecode(getMaps.getString('daily')!));
LinkedHashMap<DateTime, List<Task>> weeklyMap = jsonDecode(getMaps.getString('weekly')!);
TaskList.taskMap = dailyMap;
TaskList.weeklyTaskMap = weeklyMap;
}
void saveMapsToPrefs() async {
SharedPreferences getMaps = await _prefs;
getMaps.clear();
var dailyTasksJson = json.encode(TaskList.toJson(TaskList.taskMap));
var weeklyTasksJson = json.encode(TaskList.toJson(TaskList.weeklyTaskMap));
getMaps.setString('daily', dailyTasksJson);
getMaps.setString('weekly', weeklyTasksJson);
print("saved ${getMaps.getString('daily')}");
}
The only problem I have is decoding the JSON to my desired Map.
I hope this is understandable, if anyone needs extra information please feel free to ask :)
Thank you.
A possible quick fix could be updating your .fromJSON class method, it looks like you forgot the isCompleted field.
factory Task.fromJson(Map<String, dynamic> json) =>
Task(
isCompleted: json["isCompleted"],
taskId:json["id"],
text: json["text"],
priority: json["priority"]);
The issue was inside the fromJson() function, I was generating the list from an invalid variable
Updated method:
static LinkedHashMap<DateTime, List<Task>> fromJson(Map<String, dynamic> json) {
LinkedHashMap<DateTime, List<Task>> tempMap = LinkedHashMap<DateTime, List<Task>>();
json.forEach((key, value) {
tempMap.addAll({DateTime.parse(key): **List<Task>.from(value.map((x) => Task.fromJson(x)))**
});
});
return tempMap;
}

from json to object dart

Good afternoon, I may have found a small error, but I can't figure it out until now..
I have the following class in dart, the purpose of this class is to receive json and transform each field to object
class Attributes {
final String lpn; //itemId
final String type; //itemType (REEL,FEEDER,ETC)
final String feederContainer; //containerId
final String feederSide; //locationInContainer(A o B)
final String locationInTool; //locationInTool
Attributes(
{required this.lpn,
required this.type,
required this.feederContainer,
required this.feederSide,
required this.locationInTool});
factory Attributes.fromJson(Map json) {
return Attributes(
lpn: json['itemId'],
type: json['itemType'],
feederContainer: json['containerId'],
feederSide: json['locationInContainer'],
locationInTool: json['locationInTool'],
);
}
}
class PartNumberAt {
final String partNumber; //partNumber
final String quantity; //quantity
final String initialQuantity; //initialQuantity
PartNumberAt(
{required this.partNumber,
required this.quantity,
required this.initialQuantity});
factory PartNumberAt.fromJson(Map json) {
return PartNumberAt(
partNumber: json['partNumber'],
quantity: json['quantity'],
initialQuantity: json['initialQuantity'],
);
}
}
//partnumber RawMaterial
class ReelPartNumber {
final PartNumberAt partNumberAt;
ReelPartNumber({required this.partNumberAt});
factory ReelPartNumber.fromJson(Map json) {
return ReelPartNumber(
partNumberAt: PartNumberAt.fromJson(json['attributes']),
);
}
}
class ReelLpn {
Attributes? attributes;
ReelPartNumber? reelPartNumber;
ReelLpn(
{required Attributes attributes, required ReelPartNumber reelPartNumber});
factory ReelLpn.fromJson(Map json) {
return ReelLpn(
attributes: Attributes.fromJson(json['attributes']),
reelPartNumber: ReelPartNumber.fromJson(json['RawMaterial']),
);
}
}
and I have a file where I make http requests, the request returns the following
{
"attributes": {
"itemId": "0605007783",
"itemKey": "14992663",
"itemType": "REEL",
"itemTypeClass": "Component Lot",
"containerId": "FA0210AEF424292",
"locationInContainer": "B",
"toolContainerId": "SMT6",
"locationInTool": "10004-B",
"quarantineLocked": "false",
"expired": "false",
"initTmst": "2022-01-20T09:40:30.969-03:00"
},
"RawMaterial": {
"attributes": {
"partNumber": "11201312001166",
"partNumberDesc": "",
"supplierId": "DEFAULT",
"quantity": "2497.0",
"initialQuantity": "5000.0",
"rejectedQuantity": "3.0",
"manualAdjustmentQuantity": "548.0"
},
}
and the request is made as follows
Future<ReelLpn?> getReelData(String lpn) async {
http.Response response = await http.get(Uri.parse(apiUrl+'/$lpn'));
if (response.statusCode == 200) {
Map data = (json.decode(response.body)); //conver to json
print(data);
ReelLpn reelLpn = ReelLpn.fromJson(data); //transform json to ReelLpn
return reelLpn;
}
return null;
}
and I call the service as follows
ReelLpn? data = await CogiscanService().getReelData('0605007783');
print(data?.attributes?.type);
my problem starts there, when I print
print(data?.attributes?.type);
it returns null, I put several prints, in the ReelL class, Attributes and PartNumber, to see if I was reading the Map correctly, and they definitely read correctly.
So why when I want to access any of the fields does it return null?
Change your ReelLpn Constructor. you are not referencing the class members... thats why its always null.
ReelLpn({required this.attributes, required this.reelPartNumber});

How to get json response in flutter using POST method?

I am beginner in flutter. Please help me get and set below json data into model in flutter. I am using POST method.
'''
{
"success": 1,
"data": {
"user_id": 2,
"email": "ajay.singhal#ollosoft1.com",
"phone": "9414905280",
"password": "1436a615e62482ba4f075c1d4a4fd94b",
"account_status": "Active",
"date_of_birth": "1953-09-07T00:00:00.000Z",
"address": "Jaipur Rajasthan",
"profile_url": "http://18.217.236.99:4200/assets/profile_img/2/RBI-keeps-policy-rate-unchanged-1.jpg",
"first_name": "Ajay",
"last_name": "singhal"
}
}
'''
Below is my Model class named UserInfoModel
import 'UserInfoDataModel.dart';
class UserInfoModel {
final int success;
final UserInfoDataModel data;
UserInfoModel(this.success, this.data);
factory UserInfoModel.fromJson(dynamic json) {
if (json['data'] != null) {
var tagObjsJson = json['data'];
UserInfoDataModel _tags =
tagObjsJson.map((tagJson) => UserInfoDataModel.fromJson(tagJson));
return UserInfoModel(json['success'] as int, _tags);
}
}
#override
String toString() {
return '{${this.success}, ${this.data}}';
}
}
Below is submodel name is UserInfoDataModel
import 'package:flutter/material.dart';
class UserInfoDataModel {
int user_id;
String email;
String phone;
String password;
String account_status;
String date_of_birth;
String address;
String profile_url;
String first_name;
String last_name;
UserInfoDataModel(
{this.user_id,
this.email,
this.phone,
this.password,
this.account_status,
this.date_of_birth,
this.address,
this.profile_url,
this.first_name,
this.last_name});
factory UserInfoDataModel.fromJson(Map<String, dynamic> json) {
return UserInfoDataModel(
user_id: json['user_id'] as int,
email: json['email'],
phone: json['phone'],
password: json['password'],
account_status: json['account_status'],
date_of_birth: json['date_of_birth'],
address: json['address'],
profile_url: json['profile_url'],
first_name: json['first_name'],
last_name: json['last_name'],
);
}
}
My APi Call is below Using POST Method
I am successfully getting response, but unable to set in model
UserInfoModel _userInfoModel;
UserInfoDataModel _userInfoDataModel;
String url = BaseURLHeaders().getBaseURl() + "userInfo";
Map headers = BaseURLHeaders().getHeader();
#override
void initState() {
// TODO: implement initState
super.initState();
getData();
}
Future<UserInfoModel> getData() async {
String user_id = "1";
var mapData = new Map<String, dynamic>();
mapData['user_id'] = user_id;
// mapData['first_name'] = firstName;
var response = await http.post(
url,
headers: headers,
body: mapData,
);
setState(() {
print("userInfoDetails: ${response.body}");
print("urlTop: ${url}");
print("headersTop: ${headers}");
print("responseCode: ${response.statusCode}");
});
if (response.statusCode == 200) {
var res = json.decode(response.body);
_userInfoModel = UserInfoModel.fromJson(res);
if (_userInfoModel.success == 1) {
var data = res["data"];
setState(() {
print("responseBody: ${res}");
print("userInfoSuccess: ${_userInfoModel.success}");
print("dataVaalue: ${data["email"]}");
print("urlBelow: ${url}");
print("headersBelow: ${headers}");
});
}
}
}
UserInfoDataModel _tags =
tagObjsJson.map((tagJson) => UserInfoDataModel.fromJson(tagJson));
here you are actually treated tagObjsJson as a list. but it is a JsonObject so there you don't want the map function.
you can access the object as
UserInfoDataModel _tags =UserInfoDataModel.fromJson(tagJson);
You can use json_serializer in flutter. See flutter docs.
If you use IntelliJ IDEA, you can use DartToJson package. It generates automatically for you and you can use fromJson and toJson method.

flutter : nested json parsing list

I am trying to call Name and Fees from my json code
it is nested array from main array of my json the main array i can deal with it but the sub array i can't
"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
],
And I can't do that because of the error here when iam tring to call 'Name' and 'Fees'
type 'List<ExtraServices>' is not a subtype of type 'String'
and this is my class for mapping tour guide data to use it in list view
class TourGuide{
String id;
String name;
String email;
String password;
List<ExtraServices> extraService;
TourGuide({
this.id,
this.name,
this.email,
this.password,
this.extraService,
});
TourGuide.fromJson(Map<String, dynamic> json){
List<dynamic> extra = json['guideExtraServices'];
List<ExtraServices> extraList = extra.map((i) => ExtraServices.fromJson(i)).toList();
id = json['id'].toString();
name = json['displayName'];
email = json['email'];
password = json['password'];
extraService=extraList;
}
}
and this is a Extra Services class which tour guide class depend on to get the sub array
class ExtraServices{
String name;
double fees;
ExtraServices({
this.name,
this.fees
});
ExtraServices.fromJson(Map<String, dynamic> json){
name = json['Name'];
fees = json['Fees'].toDouble();
}
}
my provider method for decode json using for api
Future<dynamic> tourGuideList() async {
_isLoading = true;
notifyListeners();
print('Starting request');
http.Response response = await http.get(Environment.tourGuide,
headers: Environment.requestHeader);
print('Completed request');
print('respond data : ${response.body}');
Map<String, dynamic> res = json.decode(response.body);
var results;
if (res['code'] == 200) {
print('start load tourguide');
_tourGuide = [];
res['message'].forEach((v) {
_tourGuide.add(new TourGuide.fromJson(v));
});
results = true;
} else {
results =
FailedRequest(code: 400, message: res['error'], status: false);
}
_isLoading = false;
notifyListeners();
return results;
}
and I don't know why I have an error and I can't fix it
I think your json should be like this in total:
{"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
]}
Try
// To parse this JSON data, do
//
// final tourGuide = tourGuideFromJson(jsonString);
import 'dart:convert';
TourGuide tourGuideFromJson(String str) => TourGuide.fromJson(json.decode(str));
String tourGuideToJson(TourGuide data) => json.encode(data.toJson());
class TourGuide {
List<GuideExtraService> guideExtraServices;
TourGuide({
this.guideExtraServices,
});
factory TourGuide.fromJson(Map<String, dynamic> json) => TourGuide(
guideExtraServices: List<GuideExtraService>.from(json["guideExtraServices"].map((x) => GuideExtraService.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"guideExtraServices": List<dynamic>.from(guideExtraServices.map((x) => x.toJson())),
};
}
class GuideExtraService {
String name;
int fees;
GuideExtraService({
this.name,
this.fees,
});
factory GuideExtraService.fromJson(Map<String, dynamic> json) => GuideExtraService(
name: json["Name"],
fees: json["Fees"],
);
Map<String, dynamic> toJson() => {
"Name": name,
"Fees": fees,
};
}
Please try the below code :-
First Create Model :-
class GuideResponseModel {
List<GuideExtraServicesModel> guideExtraServiceList;
GuideResponseModel({
this.guideExtraServiceList
});
factory GuideResponseModel.fromJson(Map<String, dynamic> parsedJson) {
try {
List<GuideExtraServicesModel> guideExtraServiceModelList = new List();
if (parsedJson.containsKey('guideExtraServices')) {
var countryList = parsedJson['guideExtraServices'] as List;
guideExtraServiceModelList =
countryList.map((i) => GuideExtraServicesModel.fromJson(i)).toList();
}
return GuideResponseModel(
guideExtraServiceList: guideExtraServiceModelList
);
} catch (e) {
return null;
}
}
}
class GuideExtraServicesModel {
String name;
int fees;
GuideExtraServicesModel({this.name,this.fees});
factory GuideExtraServicesModel.fromJson(Map<String, dynamic> json) {
return GuideExtraServicesModel(name: json['Name'],fees: json['Fees']);
}
}
Second User the Model:-
String jsonData = '{"guideExtraServices": [{"Name": "Limousine","Fees": 100},{"Name": "Bus","Fees": 10000},{"Name": "Mini-Bus","Fees": 5000}]}';
final dynamic jsonResponse = json.decode(jsonData);
final GuideResponseModel responseModel = GuideResponseModel.fromJson(jsonResponse);
print('======${responseModel.guideExtraServiceList[0].name}----${responseModel.guideExtraServiceList[0].fees}');

flutter parsing JSON from firebase

I just started learning about flutter and try to use ScopedModel
and I get stuck at parsing JSON,
everything works until I try to get List of detail simulation but everything that I try just fails
this is my class for project and simulation
class Project {
String idProject;
List images;
List<Simulations> simulation;
Project({
#required this.idProject,
#required this.images,
#required this.simulation
});
}
class Simulations{
String period;
int profitProject;
int roi;
Simulations({
#required this.period,
#required this.profitProject,
#required this.roi
});
}
I made a separate class to get detail for simulation
this is a sample from JSON that I get from the firebase
{
"1554182068913": {
"idProject": "project id 1",
"images": [
1554181958565,
1554181955542,
1554181960876],
"simulation": [
{
"periode": "year 1",
"profitProject": 300000,
"roi": 5,
"uniqueKey": "YyCWbHjvm"
},
{
"periode": "year 1",
"profitProject": 100000,
"roi": 3,
"uniqueKey": "CvyU4SjrX"
},
{
"periode": "year 1",
"profitProject": 2000000,
"roi": 10,
"uniqueKey": "Tb_Qr5CIA"
}
],
}
}
I made function to get the data
Future<Null> fetchProjects() {
return http.get("JSON link")
.then<Null>((http.Response response) {
final List<Project> fetchedProjectList = [];
final Map<String, dynamic> projectListData = json.decode(response.body);
if (projectListData == null) {
_isLoading = false;
notifyListeners();
return;
}
projectListData.forEach((String projectId, dynamic projectData) {
final Project project = Project(
title: projectData['title'],
location: projectData['location'],
images: projectData['images'],
simulation: ???
);
fetchedProjectList.add(project);
}
What's missing here is JSON serialization. You need to convert the response to a Dart object, similar to what has been demonstrated on this guide. In Project class, you can add a fromJson() constructor to map the data.
factory Project.fromJson(Map<String, dynamic> json) {
return Project(
idProject: json['idProject'],
images: json['images'],
simulation: json['simulation'],
);
}