hy we have a radio server with the followoing json file
{
"icestats":{
"admin":"icemaster#localhost",
"host":"online.localhost.be",
"location":"Earth",
"server_id":"Icecast 2.4.4",
"server_start":"Sun, 30 Aug 2020 10:50:52 +0200",
"server_start_iso8601":"2020-08-30T10:50:52+0200",
"source":[
{
"audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2",
"bitrate":320,
"genre":"oldies",
"ice-bitrate":320,
"ice-channels":2,
"ice-samplerate":44100,
"listener_peak":0,
"listeners":0,
"listenurl":"http://127.0.0.1:8000/mp3_320",
"server_description":"Very Oldies!",
"server_name":"loclahost",
"server_type":"audio/mpeg",
"server_url":"https://127.0.0.1:8000",
"stream_start":"Sun, 30 Aug 2020 13:45:16 +0200",
"stream_start_iso8601":"2020-08-30T13:45:16+0200",
"title":"1951: Four Knights - I Love The Sunshine Of Your Smile",
"dummy":null
},
{
"audio_bitrate":320000,
"audio_channels":2,
"audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2",
"audio_samplerate":44100,
"bitrate":320,
"genre":"oldies",
"ice-bitrate":320,
"ice-channels":2,
"ice-samplerate":44100,
"listener_peak":0,
"listeners":0,
"listenurl":"http://127.0.0.1:8000/ogg_320",
"server_description":"Very Oldies!",
"server_name":"localhost",
"server_type":"application/ogg",
"server_url":"https://127.0.0.1:8000",
"stream_start":"Sun, 30 Aug 2020 13:45:16 +0200",
"stream_start_iso8601":"2020-08-30T13:45:16+0200",
"subtype":"Vorbis",
"dummy":null
}
]
}
}
if io parse this with this model i get the error 'unexpected charcater at 1'
class Autogenerated {
Icestats icestats;
Autogenerated({this.icestats});
Autogenerated.fromJson(Map<String, dynamic> json) {
icestats = json['icestats'] != null
? new Icestats.fromJson(json['icestats'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.icestats != null) {
data['icestats'] = this.icestats.toJson();
}
return data;
}
}
class Icestats {
String admin;
String host;
String location;
String serverId;
String serverStart;
String serverStartIso8601;
List<Source> source;
Icestats(
{this.admin,
this.host,
this.location,
this.serverId,
this.serverStart,
this.serverStartIso8601,
this.source});
Icestats.fromJson(Map<String, dynamic> json) {
admin = json['admin'];
host = json['host'];
location = json['location'];
serverId = json['server_id'];
serverStart = json['server_start'];
serverStartIso8601 = json['server_start_iso8601'];
if (json['source'] != null) {
source = new List<Source>();
json['source'].forEach((v) {
source.add(new Source.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['admin'] = this.admin;
data['host'] = this.host;
data['location'] = this.location;
data['server_id'] = this.serverId;
data['server_start'] = this.serverStart;
data['server_start_iso8601'] = this.serverStartIso8601;
if (this.source != null) {
data['source'] = this.source.map((v) => v.toJson()).toList();
}
return data;
}
}
class Source {
String audioInfo;
int bitrate;
String genre;
int iceBitrate;
int iceChannels;
int iceSamplerate;
int listenerPeak;
int listeners;
String listenurl;
String serverDescription;
String serverName;
String serverType;
String serverUrl;
String streamStart;
String streamStartIso8601;
String title;
Null dummy;
int audioBitrate;
int audioChannels;
int audioSamplerate;
String subtype;
Source(
{this.audioInfo,
this.bitrate,
this.genre,
this.iceBitrate,
this.iceChannels,
this.iceSamplerate,
this.listenerPeak,
this.listeners,
this.listenurl,
this.serverDescription,
this.serverName,
this.serverType,
this.serverUrl,
this.streamStart,
this.streamStartIso8601,
this.title,
this.dummy,
this.audioBitrate,
this.audioChannels,
this.audioSamplerate,
this.subtype});
Source.fromJson(Map<String, dynamic> json) {
audioInfo = json['audio_info'];
bitrate = json['bitrate'];
genre = json['genre'];
iceBitrate = json['ice-bitrate'];
iceChannels = json['ice-channels'];
iceSamplerate = json['ice-samplerate'];
listenerPeak = json['listener_peak'];
listeners = json['listeners'];
listenurl = json['listenurl'];
serverDescription = json['server_description'];
serverName = json['server_name'];
serverType = json['server_type'];
serverUrl = json['server_url'];
streamStart = json['stream_start'];
streamStartIso8601 = json['stream_start_iso8601'];
title = json['title'];
dummy = json['dummy'];
audioBitrate = json['audio_bitrate'];
audioChannels = json['audio_channels'];
audioSamplerate = json['audio_samplerate'];
subtype = json['subtype'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['audio_info'] = this.audioInfo;
data['bitrate'] = this.bitrate;
data['genre'] = this.genre;
data['ice-bitrate'] = this.iceBitrate;
data['ice-channels'] = this.iceChannels;
data['ice-samplerate'] = this.iceSamplerate;
data['listener_peak'] = this.listenerPeak;
data['listeners'] = this.listeners;
data['listenurl'] = this.listenurl;
data['server_description'] = this.serverDescription;
data['server_name'] = this.serverName;
data['server_type'] = this.serverType;
data['server_url'] = this.serverUrl;
data['stream_start'] = this.streamStart;
data['stream_start_iso8601'] = this.streamStartIso8601;
data['title'] = this.title;
data['dummy'] = this.dummy;
data['audio_bitrate'] = this.audioBitrate;
data['audio_channels'] = this.audioChannels;
data['audio_samplerate'] = this.audioSamplerate;
data['subtype'] = this.subtype;
return data;
}
}
the code i have used i pretty simple this is the code i have used.
if i parse the same code with a simple xml structure this works but with the icecast parsing this does not succeed.
please advice me
var JsonData = 'http://127.0.0.1:8000/status-json.xsl';
var parsedJson = json.decode(JsonData);
var title = Source.fromJson(parsedJson);
is the json formatting of the icecast server incorrect ? it starts with a {
update 1
class User {
String title;
User(Map<String, dynamic> data){
title = data['title'];
}
}
Future<Source> fetchData() async{
var jsonData = 'http://online.doobeedoo.be:8000/status-json.xsl';
final response =
await http.get(jsonData); //wacht to de data is ontvangen (200)
if(response.statusCode == 200)
{
var parsedJson = json.decode(response.body); //parsen van response
var user = User(parsedJson);
return('${user.title}'); //error here (A value of type 'String' can't be returned from function 'fetchData' because it has a return type of 'Future<Source>'.)
}
else
{
throw Exception('Failed to load status.json response file');
}
}
Use the http package to make a request to your server and retrieve a response. Then parse the JSON the way your currently have it. You're currently parsing a String URL. Not a JSON.
import 'package:http/http.dart' as http;
var url = 'http://127.0.0.1:8000/status-json.xsl';
var response = await http.get(url);//Actually get the data at the URL
var parsedJson = json.decode(response.body);//Parse the response
var title = Source.fromJson(parsedJson);
Related
I was wondering if someone could help? I'm trying to load a file with json content, decode it, convert to a model/object add another element.
The way I'm trying to do this is as follows:
Flow 1: Check file exists = true -> return file object -> decode string to json -> convert to model/object -> add element -> back to json -> to string -> save file.
Flow 2: Check file exists = false -> create file -> add a json template -> return file object -> decode string to json -> convert to model/object -> add element -> back to json -> to string -> save file.
This is working on the first run (flow 1), it'll create the file, add the template then add the first new element. However, when I run it a second time (flow 2), I always get an throwback.
As we speak with the code below, the error is:
E/flutter (13140): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
E/flutter (13140): #0 FileController.writeSingleResponseToFile (package:reefcommander/controllers/FileController.dart:33:39)
E/flutter (13140): <asynchronous suspension>
E/flutter (13140):
This is the code I'm using.
FileController.dart
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:intl/intl.dart';
import 'package:reefcommander/models/ReadingsData.dart';
import 'package:reefcommander/models/SingleDataReqResponse.dart';
import 'dart:convert';
class FileController {
static String date = DateFormat("dd-MM-yyyy").format(DateTime.now());
static String template =
'{"name": "_NAME_", "friendlyName": "_FNAME_", "results": []}';
static final Map<String, String> nameDefenitions = {
'ec': 'EC',
'ph': 'pH',
'atoDayRate': 'Evap Rate',
'sumpTemp': 'Temp (sump)',
'tankTemp': 'Temp (tank)'
};
static Future<File> checkFileExists(String type) async {
readFile(type);
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
return file;
}
static writeSingleResponseToFile(SingleDataReqResponse resp) async {
final File file = await checkFileExists(resp.name.toString());
var r = Map<String, dynamic>.from(jsonDecode(await file.readAsString()));
print(r.runtimeType);
ReadingsData existingdata = ReadingsData.fromJson(r[0]);
//ReadingsData existingdata =
// r.map<ReadingsData>((json) => ReadingsData.fromJson(json));
print(existingdata);
existingdata.results!.add(Results(stamp: resp.stamp, value: resp.value));
print('DATA: ${existingdata.toJson().toString()}');
file.writeAsString(jsonEncode(existingdata.toJson().toString()));
}
static Future<void> deleteFile(String type) async {
try {
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
if (file.existsSync()) {
await file.delete();
} else {}
} catch (e) {
// Error in getting access to the file.
}
}
static Future<String> readFile(String type) async {
String text = '';
try {
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
if (file.existsSync()) {
text = await file.readAsString();
} else {
file.create(recursive: true);
String tempbase = template;
String write = tempbase
.replaceAll('_NAME_', type.toString())
.replaceAll('_FNAME_', nameDefenitions[type]!);
await file.writeAsString(write);
text = await file.readAsString();
}
} catch (e) {
print("Read error");
}
return text;
}
}
ReadingsData.dart
import 'dart:convert';
class ReadingsData {
String? name;
String? friendlyName;
List<Results>? results;
ReadingsData(
{required this.name, required this.friendlyName, required this.results});
ReadingsData.fromJson(Map<String, dynamic> json) {
name = json['name'];
friendlyName = json['friendlyName'];
if (json['results'] != null) {
results = <Results>[];
json['results'].forEach((v) {
results!.add(Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['friendlyName'] = friendlyName;
if (results != null) {
data['results'] = results!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
String? stamp;
String? value;
Results({required this.stamp, required this.value});
Results.fromJson(Map<String, dynamic> json) {
stamp = json['stamp'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['stamp'] = stamp;
data['value'] = value;
return data;
}
}
Test code
FileController.writeSingleResponseToFile(
SingleDataReqResponse(name: "test", stamp: "10:22:00", value: "2222"));
For anyone else in my situation, I've resolved it. Solution below.
static writeSingleResponseToFile(SingleDataReqResponse resp) async {
final File file = await checkFileExists(resp.name.toString());
ReadingsData existingdata =
ReadingsData.fromJson(jsonDecode(await file.readAsString()));
existingdata.results!.add(Results(stamp: resp.stamp, value: resp.value));
file.writeAsString(jsonEncode(existingdata.toJson()));
}
Sup! So my problem is, my Dashboard Model isnt getting data assigned from the json string parsed.Basically Dashboard.userActivity and Dashboard.appName are NULL when i print into console. I cant realy get behind why. the testDataFunction should print the corresponding Dashboard Object with all their data (2 nested classes Performance and UserActivity and 3 variables errors, appname,time.
I did not include the code of Perf and UserAct. as its the same as Dashboard with toJson and fromJson helper Methods.
What did i oversaw? Much thanks in advance!
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class Dashboard {
UserActivity? userActivity; ///class
int? totalError;
Performance? performance; ///class
String? appName;
String? time;
Dashboard(
{this.userActivity,
this.totalError,
this.performance,
this.appName,
this.time});
Dashboard.fromJson(Map<dynamic, dynamic> json) {
userActivity = json['userActivity'] != null
? new UserActivity.fromJson(json['userActivity'])
: null;
totalError = json['totalError'];
performance = json['performance'] != null
? new Performance.fromJson(json['performance'])
: null;
appName = json['appName'];
time = json['time'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.userActivity != null) {
data['userActivity'] = this.userActivity!.toJson();
}
data['totalError'] = this.totalError;
if (this.performance != null) {
data['performance'] = this.performance!.toJson();
}
data['appName'] = this.appName;
data['time'] = this.time;
return data;
}
#override
toString() {
return "userActivity: " + userActivity.toString() + ", appName: " + appName!;
}
}
Future testDataFunktion() async {
String backendjsondata = '{"dashboard":{"userActivity":{"total":17,"logins":50,"active":1,"inactive":5,"loginsPerHourLst":[0,0,0,0,0,0,0,4,11,13,3,3,0,0,10,6],"hourLst":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],"online":6},"totalError":1,"performance":{"loadTimePagesLst":[583,289,154,105,16,13,4,583,0,0],"totalPageViewsPerHourLst":[0,0,0,0,0,0,0,14,82,104,52,85,9,89,114,34],"hourLst":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],"totalPageViews":583},"appName":"intranet","time":"January, 24 2022 15:50:48"}}';
Map<String, dynamic> data = jsonDecode(backendjsondata);
Dashboard dashboard = Dashboard.fromJson(data);
print(dashboard);
Try:
Future testDataFunktion() async {
String backendjsondata = '{"dashboard":{"userActivity":{"total":17,"logins":50,"active":1,"inactive":5,"loginsPerHourLst":[0,0,0,0,0,0,0,4,11,13,3,3,0,0,10,6],"hourLst":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],"online":6},"totalError":1,"performance":{"loadTimePagesLst":[583,289,154,105,16,13,4,583,0,0],"totalPageViewsPerHourLst":[0,0,0,0,0,0,0,14,82,104,52,85,9,89,114,34],"hourLst":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],"totalPageViews":583},"appName":"intranet","time":"January, 24 2022 15:50:48"}}';
Dashboard dashboard = Dashboard.fromJson(Map.from(jsonDecode(backendjsondata)));
print(dashboard);
}
I have a complex JSON object and I already converted it to dart code using JSON to Dart plugin. I have created a View Model to call my API and update the provider. However, the provider doesn't seem to work.
The API response is successful but I get this error message ->
The following NoSuchMethodError was thrown building Builder: The getter 'replyStatus' was called on null. Receiver: null Tried calling: replyStatus
Can anyone help me to solve this issue?
Below is the code I have.
JSON to Dart Response
class UserProfile {
int replyStatus;
String replyDesc;
int debugStep;
bool hasData;
int actualDataSize;
List<ResultObjectSet> resultObjectSet;
dynamic token;
UserProfile(
{this.replyStatus,
this.replyDesc,
this.debugStep,
this.hasData,
this.actualDataSize,
this.resultObjectSet,
this.token});
UserProfile.fromJson(Map<String, dynamic> json) {
replyStatus = json['ReplyStatus'];
replyDesc = json['ReplyDesc'];
debugStep = json['DebugStep'];
hasData = json['HasData'];
actualDataSize = json['ActualDataSize'];
if (json['ResultObjectSet'] != null) {
// ignore: deprecated_member_use
resultObjectSet = new List<ResultObjectSet>();
json['ResultObjectSet'].forEach((v) {
resultObjectSet.add(new ResultObjectSet.fromJson(v));
});
}
token = json['Token'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ReplyStatus'] = this.replyStatus;
data['ReplyDesc'] = this.replyDesc;
data['DebugStep'] = this.debugStep;
data['HasData'] = this.hasData;
data['ActualDataSize'] = this.actualDataSize;
if (this.resultObjectSet != null) {
data['ResultObjectSet'] =
this.resultObjectSet.map((v) => v.toJson()).toList();
}
data['Token'] = this.token;
return data;
}
}
class ResultObjectSet {
String objectName;
ObjectSet objectSet;
ResultObjectSet({this.objectName, this.objectSet});
ResultObjectSet.fromJson(Map<String, dynamic> json) {
objectName = json['ObjectName'];
objectSet = json['ObjectSet'] != null
? new ObjectSet.fromJson(json['ObjectSet'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ObjectName'] = this.objectName;
if (this.objectSet != null) {
data['ObjectSet'] = this.objectSet.toJson();
}
return data;
}
}
class ObjectSet {
int userId;
String userName;
String regsterEmail;
String lastLogin;
double displayTimeZone;
int accountStatus;
int language;
List<UserCompany> userCompany;
MenuOption menuOption;
bool pnmDisableFlag;
ObjectSet(
{this.userId,
this.userName,
this.regsterEmail,
this.lastLogin,
this.displayTimeZone,
this.accountStatus,
this.language,
this.userCompany,
this.menuOption,
this.pnmDisableFlag});
ObjectSet.fromJson(Map<String, dynamic> json) {
userId = json['UserId'];
userName = json['UserName'];
regsterEmail = json['RegsterEmail'];
lastLogin = json['LastLogin'];
displayTimeZone = json['DisplayTimeZone'];
accountStatus = json['AccountStatus'];
language = json['Language'];
if (json['UserCompany'] != null) {
// ignore: deprecated_member_use
userCompany = new List<UserCompany>();
json['UserCompany'].forEach((v) {
userCompany.add(new UserCompany.fromJson(v));
});
}
menuOption = json['MenuOption'] != null
? new MenuOption.fromJson(json['MenuOption'])
: null;
pnmDisableFlag = json['PnmDisableFlag'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['UserId'] = this.userId;
data['UserName'] = this.userName;
data['RegsterEmail'] = this.regsterEmail;
data['LastLogin'] = this.lastLogin;
data['DisplayTimeZone'] = this.displayTimeZone;
data['AccountStatus'] = this.accountStatus;
data['Language'] = this.language;
if (this.userCompany != null) {
data['UserCompany'] = this.userCompany.map((v) => v.toJson()).toList();
}
if (this.menuOption != null) {
data['MenuOption'] = this.menuOption.toJson();
}
data['PnmDisableFlag'] = this.pnmDisableFlag;
return data;
}
}
class UserCompany {
int companyId;
String companyName;
int typeUserRoleId;
String typeUserRoleDesc;
int menuRights;
int reportRights;
ManagementCompanyRights managementCompanyRights;
ManagementCompanyRights managementUserRights;
ManagementCompanyRights managementUserRole;
ManagementCompanyRights managementFleetRights;
ManagementCompanyRights managementShipRights;
UserCompany(
{this.companyId,
this.companyName,
this.typeUserRoleId,
this.typeUserRoleDesc,
this.menuRights,
this.reportRights,
this.managementCompanyRights,
this.managementUserRights,
this.managementUserRole,
this.managementFleetRights,
this.managementShipRights});
UserCompany.fromJson(Map<String, dynamic> json) {
companyId = json['CompanyId'];
companyName = json['CompanyName'];
typeUserRoleId = json['TypeUserRoleId'];
typeUserRoleDesc = json['TypeUserRoleDesc'];
menuRights = json['MenuRights'];
reportRights = json['ReportRights'];
managementCompanyRights = json['ManagementCompanyRights'] != null
? new ManagementCompanyRights.fromJson(json['ManagementCompanyRights'])
: null;
managementUserRights = json['ManagementUserRights'] != null
? new ManagementCompanyRights.fromJson(json['ManagementUserRights'])
: null;
managementUserRole = json['ManagementUserRole'] != null
? new ManagementCompanyRights.fromJson(json['ManagementUserRole'])
: null;
managementFleetRights = json['ManagementFleetRights'] != null
? new ManagementCompanyRights.fromJson(json['ManagementFleetRights'])
: null;
managementShipRights = json['ManagementShipRights'] != null
? new ManagementCompanyRights.fromJson(json['ManagementShipRights'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['CompanyId'] = this.companyId;
data['CompanyName'] = this.companyName;
data['TypeUserRoleId'] = this.typeUserRoleId;
data['TypeUserRoleDesc'] = this.typeUserRoleDesc;
data['MenuRights'] = this.menuRights;
data['ReportRights'] = this.reportRights;
if (this.managementCompanyRights != null) {
data['ManagementCompanyRights'] = this.managementCompanyRights.toJson();
}
if (this.managementUserRights != null) {
data['ManagementUserRights'] = this.managementUserRights.toJson();
}
if (this.managementUserRole != null) {
data['ManagementUserRole'] = this.managementUserRole.toJson();
}
if (this.managementFleetRights != null) {
data['ManagementFleetRights'] = this.managementFleetRights.toJson();
}
if (this.managementShipRights != null) {
data['ManagementShipRights'] = this.managementShipRights.toJson();
}
return data;
}
}
class ManagementCompanyRights {
bool add;
bool edit;
bool delete;
bool fleetAssignment;
ManagementCompanyRights(
{this.add, this.edit, this.delete, this.fleetAssignment});
ManagementCompanyRights.fromJson(Map<String, dynamic> json) {
add = json['Add'];
edit = json['Edit'];
delete = json['Delete'];
fleetAssignment = json['FleetAssignment'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Add'] = this.add;
data['Edit'] = this.edit;
data['Delete'] = this.delete;
data['FleetAssignment'] = this.fleetAssignment;
return data;
}
}
class MenuOption {
bool dashBoard;
bool fuelCons;
bool bunkering;
bool aMS;
bool shaftPower;
bool kpiPerformance;
bool eOM;
bool route;
bool report;
bool management;
MenuOption(
{this.dashBoard,
this.fuelCons,
this.bunkering,
this.aMS,
this.shaftPower,
this.kpiPerformance,
this.eOM,
this.route,
this.report,
this.management});
MenuOption.fromJson(Map<String, dynamic> json) {
dashBoard = json['DashBoard'];
fuelCons = json['FuelCons'];
bunkering = json['Bunkering'];
aMS = json['AMS'];
shaftPower = json['ShaftPower'];
kpiPerformance = json['KpiPerformance'];
eOM = json['EOM'];
route = json['Route'];
report = json['Report'];
management = json['Management'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['DashBoard'] = this.dashBoard;
data['FuelCons'] = this.fuelCons;
data['Bunkering'] = this.bunkering;
data['AMS'] = this.aMS;
data['ShaftPower'] = this.shaftPower;
data['KpiPerformance'] = this.kpiPerformance;
data['EOM'] = this.eOM;
data['Route'] = this.route;
data['Report'] = this.report;
data['Management'] = this.management;
return data;
}
}
Main.Dart
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => UserVM(),
),
],
child: MaterialApp(
initialRoute: LoginScreen.id,
routes: {
LoginScreen.id: (context) => LoginScreen(),
SelectCompany.id: (context) => SelectCompany(),
},
),
);
}
}
My API class
class LoginScreenApi {
var dio = Dio();
Future<UserProfile> authenticateUser(
String email, String password, String token) async {
try {
String queryURL =
'$domainURL/User/LoginMobile?Email=$email&UserPassword=$password&MobileDeviceTokenId=$token';
Response response = await dio.get(queryURL);
print('login status: ${response.statusCode}');
if (response.statusCode == 200) {
UserProfile user = UserProfile.fromJson(response.data);
return user;
}
return null;
} catch (e) {
print(e);
return null;
}
}
}
My VM class
class UserVM extends ChangeNotifier {
UserProfile user;
UserVM({this.user});
/// Call Login API
Future<void> authenticateUser(
String email, String password, String token) async {
final results =
await LoginScreenApi().authenticateUser(email, password, token);
/// if login successfully, save the USER result and route to select company page
if (results != null) {
this.user = results;
notifyListeners();
Navigator.pushNamed(navigatorKey.currentContext, SelectCompany.id);
} else {
showDialog(
context: navigatorKey.currentContext,
builder: (BuildContext context) {
return PopUpDialog(
text: 'Wrong User ID or Password!',
);
});
}
}
}
The screen that I display the data from my provider
class _SelectCompanyState extends State<SelectCompany> {
#override
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Text(
'${Provider.of<UserVM>(context, listen: false).replyStatus}',
style: TextStyle(color: Colors.black),
),
),
);
}
}
The Widget that call the Authenticate method at my login screen
Widget _loginButton() {
// ignore: deprecated_member_use
return RaisedButton(
onPressed: () async {
await user.authenticateUser(email, password, deviceToken);
setState(() {
showSpinner = true;
});
},
color: Colors.black,
child: Text(
'${userLanguage == 'chinese' ? '登入' : 'Login'}',
style:
TextStyle(fontSize: 15, color: Colors.yellow, fontFamily: 'Roboto'),
),
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.lightBlueAccent)),
);
}
The following line loads an instance of your UserVM.
final userVM = Provider<UserVM>.of(context,listen:false);
Your UserVM class doesn't have a property called replyStatus, it's your UserProfile class that does. So call it like this:
final replyStatus = userVM.user.replyStatus;
Note: Your user can also be null since you're not passing it while creating the UserVM(). Neither are you calling the authenticate method for user to be updated with results. If you're handling that somewhere else in your code that's fine else you need to check user for null as well before calling:
final replyStatus;
If(userVM.user! = null) replyStatus = userVM.user.replyStatus;
else //<-- some alternative here
I want to fetch dat form some API and parse its data to model.
MyModel:
class SetupIdeaModel {
String id;
String userId;
String typeIdea = "Implemented Idea";
String category; //Or Industry
String experienceYear;
String experienceMonth;
String ideaHeadline;
String ideaText;
Map timeline = {
"timelineType": "date",
"details": null,
};
List documents = [];
Map uploadVideo;
String location;
String estimatedPeople;
Map whitePaper;
bool needServiceProvider = false;
bool needInvestor = true;
}
}
and I fetch data from the API with the getIdeaList method:
getIdeaList method
Future getIdeaList(String token) async {
Response response = await APIRequest().get(
myUrl: "$baseUrl/innovator/idea/list",
token: token,
);
//Parsing ideaList to SetupIdeaModel
ideas = List();
try {
(response.data as List).forEach((element) {
SetupIdeaModel idea = new SetupIdeaModel();
var months = int.parse(element["industryExperienceInMonth"]);
var year = (months / 12).floor();
var remainderMonths = months % 12;
print("$year year and $remainderMonths months");
idea.id = element["_id"];
idea.userId = element["userId"];
idea.typeIdea = element["ideaType"];
idea.category = element["industry"];
idea.experienceYear = year.toString();
idea.experienceMonth = remainderMonths.toString();
idea.ideaHeadline = element["headline"];
idea.ideaText = element["idea"];
idea.estimatedPeople = element["estimatedPeople"].toString();
print("Documents ${element["uploadDocuments"]}");
idea.location = element["targetAudience"];
idea.documents = element["uploadDocuments"];
// idea.timeline = element["timeline"];
// idea.uploadVideo = element["uploadVideo"];
ideas.add(idea);
});
} catch (e) {
print("Error: $e");
}
print("ideas $ideas");
notifyListeners();
}
Everything is OK but When I add one of these line:
idea.documents = element["uploadDocuments"];
idea.timeline = element["timeline"];
idea.uploadVideo = element["uploadVideo"];
I have got the error.
The data comes for the API is like this:
[
{
"industryExperienceInMonth":30,
"estimatedPeople":200,
"needServiceProvider":true,
"needInvestor":true,
"_id":5fcc681fc5b4260011810112,
"userId":5fb6650eacc60d0011910a9b,
"ideaType":"Implemented Idea",
"industry":"Technalogy",
"headline":"IDea headline",
"idea":"This is aobut your idea",
"timeline":{
"timelineType":"date",
"details":{
"date":Dec 6,
2020
}
},
"uploadDocuments":[
{
"_id":5fcc6804c5b4260011810110,
"uriPath":"https"://webfume-onionai.s3.amazonaws.com/guest/public/document/741333-beats_by_dre-wallpaper-1366x768.jpg
}
],
"uploadVideo":{
"_id":5fcc681ac5b4260011810111,
"uriPath":"https"://webfume-onionai.s3.amazonaws.com/guest/public/video/588700-beats_by_dre-wallpaper-1366x768.jpg
},
"targetAudience":"heart",
"__v":0
}
]
I'm using Dio package.
The documents in the model is a list and the uploadDocuments the come form API is a list too. But Why I got this error.
Your JSON data has some syntax errors that's why it's not working. All the UIDs and URLs should be in string format and you should Serializing JSON inside model classes. see also
I have fix some error in your code and did some improvement :
Future getIdeaList(String token) async {
List<SetupIdeaModel> setupIdeaModel = List();
try {
Response response = await APIRequest().get(
myUrl: "$baseUrl/innovator/idea/list",
token: token,
);
if (response.statusCode == 200) {
List<SetupIdeaModel> apiData = (json.decode(utf8.decode(response.data)) as List)
.map((data) => new SetupIdeaModel.fromJson(data))
.toList();
setupIdeaModel.addAll(apiData);
}
} catch (e) {
print("Error: $e");
}
}
This is the model class :
class SetupIdeaModel {
int industryExperienceInMonth;
int estimatedPeople;
bool needServiceProvider;
bool needInvestor;
String sId;
String userId;
String ideaType;
String industry;
String headline;
String idea;
Timeline timeline;
List<UploadDocuments> uploadDocuments;
UploadDocuments uploadVideo;
String targetAudience;
int iV;
SetupIdeaModel(
{this.industryExperienceInMonth,
this.estimatedPeople,
this.needServiceProvider,
this.needInvestor,
this.sId,
this.userId,
this.ideaType,
this.industry,
this.headline,
this.idea,
this.timeline,
this.uploadDocuments,
this.uploadVideo,
this.targetAudience,
this.iV});
SetupIdeaModel.fromJson(Map<String, dynamic> json) {
industryExperienceInMonth = json['industryExperienceInMonth'];
estimatedPeople = json['estimatedPeople'];
needServiceProvider = json['needServiceProvider'];
needInvestor = json['needInvestor'];
sId = json['_id'];
userId = json['userId'];
ideaType = json['ideaType'];
industry = json['industry'];
headline = json['headline'];
idea = json['idea'];
timeline = json['timeline'] != null
? new Timeline.fromJson(json['timeline'])
: null;
if (json['uploadDocuments'] != null) {
uploadDocuments = new List<UploadDocuments>();
json['uploadDocuments'].forEach((v) {
uploadDocuments.add(new UploadDocuments.fromJson(v));
});
}
uploadVideo = json['uploadVideo'] != null
? new UploadDocuments.fromJson(json['uploadVideo'])
: null;
targetAudience = json['targetAudience'];
iV = json['__v'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['industryExperienceInMonth'] = this.industryExperienceInMonth;
data['estimatedPeople'] = this.estimatedPeople;
data['needServiceProvider'] = this.needServiceProvider;
data['needInvestor'] = this.needInvestor;
data['_id'] = this.sId;
data['userId'] = this.userId;
data['ideaType'] = this.ideaType;
data['industry'] = this.industry;
data['headline'] = this.headline;
data['idea'] = this.idea;
if (this.timeline != null) {
data['timeline'] = this.timeline.toJson();
}
if (this.uploadDocuments != null) {
data['uploadDocuments'] =
this.uploadDocuments.map((v) => v.toJson()).toList();
}
if (this.uploadVideo != null) {
data['uploadVideo'] = this.uploadVideo.toJson();
}
data['targetAudience'] = this.targetAudience;
data['__v'] = this.iV;
return data;
}
}
class Timeline {
String timelineType;
Details details;
Timeline({this.timelineType, this.details});
Timeline.fromJson(Map<String, dynamic> json) {
timelineType = json['timelineType'];
details =
json['details'] != null ? new Details.fromJson(json['details']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['timelineType'] = this.timelineType;
if (this.details != null) {
data['details'] = this.details.toJson();
}
return data;
}
}
class Details {
String date;
Details({this.date});
Details.fromJson(Map<String, dynamic> json) {
date = json['date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['date'] = this.date;
return data;
}
}
class UploadDocuments {
String sId;
String uriPath;
UploadDocuments({this.sId, this.uriPath});
UploadDocuments.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
uriPath = json['uriPath'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['uriPath'] = this.uriPath;
return data;
}
}
I am trying to read a JSON code which is compatible with a Swift program into a flutter app. The structure is like this:
{
"tagDict" : {
"abc" : {
"helpHdr" : "short text1",
"helpText" : "long text1"
},
"def" : {
"helpHdr" : "short text2",
"helpText" : "long text2"
}
}
}
This creates in Swift a dictionary and shall create a map in Dart of the type {key : {helpHdr, helpText}}. A variable based on this should enable label = myVariable[tag].helpHdr, or staying with the example label = myVariable["abc"].helpHdr should assign "short text1" to label
To parse nested arrays I am using this, however, no clue how to transfer this to such a nested map.
class MyClass {
List<MySubClass> myArray;
MyClass({
this.myArray,
});
factory MyClass.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['myArray'] as List;
List<MySubClass> listObject = list.map((i) => MySubClass.fromJson(i)).toList();
return new MyClass(
myArray: listObject,
);
}
}
class MySubClass {
int id;
String text1;
String text2;
MySubClass({
this.id,
this.text1,
this.text2,
});
factory MySubClass.fromJson(Map<String, dynamic> parsedJson){
return new MySubClass(
id: parsedJson['id'],
text1: parsedJson['text1'],
text2: parsedJson['text2'],
);
}
}
If I'm correct you want to parse your json into Data class object. If that's right then you can try this
void main() {
List<MyClass> myClassList = new List<MyClass>();
Map map = {
"tagDict": {
"abc": {"helpHdr": "short text1", "helpText": "long text1"},
"def": {"helpHdr": "short text2", "helpText": "long text2"}
}
};
map['tagDict'].forEach((key, value) {
value['id'] = key;
myClassList.add(MyClass.fromJson(value));
});
myClassList.forEach((myClass) {
print(myClass.id);
print(myClass.helpHdr);
print(myClass.helpText);
print("--------------------\n");
});
}
class MyClass {
String id;
String helpHdr;
String helpText;
MyClass({this.id, this.helpHdr, this.helpText});
MyClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
This is the Output:
abc
short text1
long text1
--------------------
def
short text2
long text2
--------------------
class TagRes {
TagDict tagDict;
TagRes({this.tagDict});
TagRes.fromJson(Map<String, dynamic> json) {
tagDict =
json['tagDict'] != null ? new TagDict.fromJson(json['tagDict']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.tagDict != null) {
data['tagDict'] = this.tagDict.toJson();
}
return data;
}
}
class TagDict {
Abc abc;
Abc def;
TagDict({this.abc, this.def});
TagDict.fromJson(Map<String, dynamic> json) {
abc = json['abc'] != null ? new Abc.fromJson(json['abc']) : null;
def = json['def'] != null ? new Abc.fromJson(json['def']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.abc != null) {
data['abc'] = this.abc.toJson();
}
if (this.def != null) {
data['def'] = this.def.toJson();
}
return data;
}
}
class Abc {
String helpHdr;
String helpText;
Abc({this.helpHdr, this.helpText});
Abc.fromJson(Map<String, dynamic> json) {
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
Based on Tipu's answer, I came up with the following code which creates the intended dictionary (or map in Dart - why couldn't they stick to standard terminology like arrays etc?!)
class TaskTags {
var tagDict = Map<String, TaskTag>();
TaskTags({
this.tagDict,
});
factory TaskTags.fromJson(Map<String, dynamic> json){
var innerMap = json['tagDict'];
var tagMap = Map<String, TaskTag>();
innerMap.forEach((key, value) {
tagMap.addAll({key: TaskTag.fromJson(value)});
});
return new TaskTags(
tagDict: tagMap,
);
}
}
class TaskTag {
String helpHdr;
String helpText;
TaskTag({
this.helpHdr,
this.helpText,
});
factory TaskTag.fromJson(Map<String, dynamic> json){
return new TaskTag(
helpHdr: json['helpHdr'],
helpText: json['helpText'],
);
}
}
This creates the following map
{"abc“ : {helpHdr: "short text1", helpText: "long text1"}, "def“ : {helpHdr: "short text2", helpText: "long text2"}}