I am using the following code to verify stock data:
Future<Stock> verifyIfStockSymbolIsValid(String symbol) async {
final response =
await http.get('https://cloud.iexapis.com/stable/stock/$symbol/quote?token=my-token');
if (response.statusCode == 200) {
// Get Map from JSON.
Map data = json.decode(response.body);
print(data); // here the data (output below) is printed!
Map quoteData = data['quote'];
Stock stockQuote = Stock.fromJson(quoteData); // here should be the problem
return stockQuote;
} else {
return null;
}
}
The output looks like this:
I/flutter ( 9290): {symbol: XOM, companyName: Exxon Mobil Corp., primaryExchange: NEW YORK STOCK EXCHANGE, INC., calculationPrice: tops, open: null, openTime: null, openSource: official, close: null, closeTime: null, closeSource: official, high: null, highTime: 1608044090030, highSource: 15 minute delayed price, low: null, lowTime: 1608044281245, lowSource: IEX real time price, latestPrice: 42.52, latestSource: IEX real time price, latestTime: 10:09:34 AM, latestUpdate: 1608044974460, latestVolume: null, iexRealtimePrice: 42.52, iexRealtimeSize: 100, iexLastUpdated: 1608044974460, delayedPrice: null, delayedPriceTime: null, oddLotDelayedPrice: null, oddLotDelayedPriceTime: null, extendedPrice: null, extendedChange: null, extendedChangePercent: null, extendedPriceTime: null, previousClose: 42.22, previousVolume: 30595042, change: 0.3, changePercent: 0.00711, volume: null, iexMarketPercent: 0.01788127392568208, iexVolume: 65063, avgTotalVolume: 30683847, iexBidPrice: 41.99, iexBidSize: 100, iexAskPrice: 42.51, iexAskSize: 400, iexOpen: 42.475, iexOpenTime: 1608052428625, iexClose: 42.475, iexCloseTime: 1608052428625, marketCap: 179594243992, peRatio: 54.63, week52High: 65.66, week52Low: 29.54, ytdChange: -0.3405948289133432, lastTradeTime: 1608052428625, isUSMarketOpen: true}
E/flutter ( 9290): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 9290): Receiver: null
E/flutter ( 9290): Tried calling:
And my stock class is looking like that:
class Stock {
final String companyName;
final String symbol;
// The following are dynamic as using double generates an error
// when the API returns values with no decimal (e.g. 12 vs 12.0).
final dynamic latestPrice;
final dynamic low;
final dynamic high;
final dynamic week52High;
final dynamic change;
final dynamic changePercent;
final dynamic peRatio;
final dynamic previousClose;
// Default constructor.
Stock(this.companyName, this.symbol, this.latestPrice,
this.low, this.high, this.week52High, this.change,
this.changePercent, this.peRatio, this.previousClose);
// Named constructor, create object from JSON.
Stock.fromJson(Map<String, dynamic> json)
: companyName = (json['companyName'] != null ? json['companyName'] : ""),
symbol = (json['symbol'] != null ? json['symbol'] : ""),
latestPrice = (json['latestPrice'] != null ? json['latestPrice'] : 0.0),
low = (json['low'] != null ? json['low'] : 0.0),
high = (json['high'] != null ? json['high'] : 0.0),
week52High = (json['week52High'] != null ? json['week52High'] : 0.0),
change = (json['change'] != null ? json['change'] : 0.0),
changePercent = (json['changePercent'] != null ? json['changePercent'] : 0.0),
peRatio = (json['peRatio'] != null ? json['peRatio'] : 0.0),
previousClose = (json['previousClose'] != null ? json['previousClose'] : 0.0);
}
How can I solve this?
final data = json.decode(response.body) as Map;
print(data); // here the data (output below) is printed!
final quoteData = data['quote'] as Map;
Casting is imp , try this and let me know too..
replace only 3 lines above
Related
I'm trying to get some data from a cloud function and assign it to a model. But I am unable to used the nested data, I get the following error:
_TypeError (type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>')
The data I receive looks like this:
{
"answer": "Some optional answer",
"error": "Some optional error",
"usage": { "prompt_tokens": 32, "completion_tokens": 40, "total_tokens": 72 }
}
When I receive the data I try to assign it to a model:
final HttpsCallableResult result = await functions
.httpsCallable('askHW')
.call({'question': userQuestion});
return HWResponse.fromJson(result.data);
HWResoponse:
class HWResponse {
final String answer;
final String error;
final HWUsage usage;
HWResponse({this.answer = '', this.error = '', required this.usage});
factory HWResponse.fromJson(Map<String, dynamic> json) => HWResponse(
answer: json.containsKey('answer') ? json['answer'] as String : '',
error: json.containsKey('error') ? json['error'] as String : '',
usage:
json["usage"] == null ? HWUsage() : HWUsage.fromJson(json["usage"]),
);
Map<String, dynamic> toJson() => {
"answer": answer,
"error": error,
"usage": usage.toJson(),
};
}
class HWUsage {
final int promptTokens;
final int completionTokens;
final int totalTokens;
HWUsage({
this.promptTokens = 0,
this.completionTokens = 0,
this.totalTokens = 0,
});
factory HWUsage.fromJson(Map<String, dynamic> json) => HWUsage(
promptTokens: json.containsKey('prompt_tokens')
? json['prompt_tokens'] as int
: 0,
completionTokens: json.containsKey('completion_tokens')
? json['completion_tokens'] as int
: 0,
totalTokens:
json.containsKey('total_tokens') ? json['total_tokens'] as int : 0,
);
Map<String, dynamic> toJson() => {
"prompt_tokens": promptTokens,
"completion_tokens": completionTokens,
"total_tokens": totalTokens,
};
}
Using Map<String, dynamic>.from('json['usage]') in HWResponse on the nested field seems to be the correct way to do this. To avoid any errors I also used json.containsKey('usage') to make sure that the nested field usage actually exists.
usage: json.containsKey('usage')
? HWUsage.fromJson(Map<String, dynamic>.from(json['usage']))
: HWUsage(),
Can I get some help with this please...I am getting error like
1) near "VALUES": syntax error
I/flutter ( 6415): DatabaseException(near "VALUES": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO words (
here is my dart model code..it says something is wrong here
[Here][1]
Wordtable is my SQLite model where I'm saving the data and Word is my backend model where I'm fetching the data to save into SQLite one
I tried to make it short and precise as possible so please do let me know if any further clarification is needed.
Thank you and happy new year
class WordList {
List<Word>? words;
WordList({this.words});
factory WordList.fromJson(List<dynamic> json, String lang) {
List<Word> words = json.map((i) => Word.fromJson(i, lang)).toList();
return new WordList(
words: words,
);
}
}
class WordTableList {
final List<WordTable>? words;
WordTableList({this.words});
factory WordTableList.fromJson(List<dynamic> json) {
List<WordTable> words = json.map((e) => WordTable.fromMap(e)).toList();
return new WordTableList(
words: words,
);
}
}
////////////////////WordTable SQLLITE/////////////////////
class WordTable {
static String table = 'words';
int? WORD_ID;
String? TINA;
String? LETTER;
String? NABA;
String? ITAVI;
String? LOMANIBAI;
String? DEWA;
String? IVAKAMACALA;
String? COKE;
String? IDUSIDUSI;
// String? LINKED_SYN;
String? IVOSAVOSA;
String? ITAKATAKA;
String? VOSA_VAKALATINA;
String? WORDIMG;
String? MAIN_AUDIO;
String? STORY_AUDIO;
WordTable.fromJson(Map<String, dynamic> json) {
this.WORD_ID = json['word_id'];
this.TINA = json['tina'];
this.LETTER = json['letter'];
this.NABA = json['naba'];
this.ITAVI = json['itavi'];
this.LOMANIBAI = json['lomanibai'];
this.DEWA = json['dewa'];
this.IVAKAMACALA = json['ivakamacala'];
this.COKE = json['coke'];
this.IDUSIDUSI = json['idusidusi'];
//this.LINKED_SYN = json['ivosavosa'];
this.IVOSAVOSA = json['ivosavosa'];
this.ITAKATAKA = json['itakataka'];
this.VOSA_VAKALATINA = json['vosa_vakalatina'];
this.WORDIMG = json['word_main_image'];
this.MAIN_AUDIO = json['word_main_audio'];
this.STORY_AUDIO = json['story_audio'];
// if (json['family'] != null) {
// this.plantFamily = PlantFamily.fromJson(json['family']);
// }
}
WordTable.fromMap(Map<String, dynamic> json) {
this.WORD_ID = json['word_id'] == null ? 0 : json['word_id'];
this.TINA =
json['tina'] == null ? "No Scientific Name Available" : json['tina'];
this.LETTER =
json['letter'] == null ? "No Local Name Available" : json['letter'];
this.NABA = json['naba'] == null
? "storage/images/13293205681610263850.png"
: json['naba'];
this.ITAVI =
json['itavi'] == null ? "No Description Available" : json['itavi'];
this.LOMANIBAI = json['lomanibai'] == null
? "No Description Available"
: json['lomanibai'];
this.DEWA =
json['dewa'] == null ? "No Distribution Available" : json['dewa'];
this.IVAKAMACALA = json['ivakamacala'] == null
? "No Distribution Available"
: json['ivakamacala'];
this.COKE =
json['coke'] == null ? "No Distribution Available" : json['coke'];
this.IDUSIDUSI = json['idusidusi'] == null
? "No Description Available"
: json['idusidusi'];
this.IVOSAVOSA = json['ivosavosa'] == null
? "No Description Available"
: json['ivosavosa'];
this.ITAKATAKA = json['itakataka'] == null
? "No Description Available"
: json['itakataka'];
this.VOSA_VAKALATINA = json['vosa_vakalatina'] == null
? "No Description Available"
: json['vosa_vakalatina'];
this.WORDIMG = json['word_main_image'] == null
? "No Description Available"
: json['word_main_image'];
this.MAIN_AUDIO = json['word_main_audio'] == null
? "No Description Available"
: json['word_main_audio'];
this.STORY_AUDIO = json['story_audio'] == null
? "No Description Available"
: json['story_audio'];
// this.hpfMedicalUseOtherFj = json['hpf_medical_use_other_fj'] == null
// ? "No Description Available"
// : json['hpf_medical_use_other_fj'];
// if (json['plant_family'] != null) {
// print('family is not null');
// this.plantFamily = new PlantFamily(
// bookChapterId: 0,
// hpfBotanicalCat: json['plant_botanical_category'],
// hpfBotanicalSubCat: json['plant_sub_botanical_category'],
// hpfFamilyName: json['plant_family'],
// id: 0);
//}
}
static String plantTableQuery(WordTable words) {
return ''' INSERT INTO words (
word_id,
tina,
letter,
naba,
itavi,
lomanibai,
dewa,
ivakamacala,
coke,
idusidusi,
ivosavosa,
itakataka,
vosa_vakalatina,
word_main_image,
word_main_audio,
story_audio,
VALUES (
'${words.WORD_ID}',
'${words.TINA}',
'${words.LETTER}',
'${words.NABA}',
'${words.ITAVI}',
'${words.LOMANIBAI}',
'${words.DEWA}',
'${words.IVAKAMACALA}',
'${words.COKE}',
'${words.IDUSIDUSI}',
'${words.IVOSAVOSA}',
'${words.ITAKATAKA}',
'${words.VOSA_VAKALATINA}',
'${words.WORDIMG}',
'${words.MAIN_AUDIO}',
'${words.STORY_AUDIO}'
)''';
}
static const String CREATE_TABLE = '''CREATE TABLE IF NOT EXISTS words (
word_id INTEGER PRIMARY KEY,
tina TEXT,
letter TEXT,
naba TEXT,
itavi TEXT,
lomanibai TEXT,
dewa TEXT,
ivakamacala TEXT,
coke TEXT,
idusidusi TEXT,
ivosavosa TEXT,
itakataka TEXT,
vosa_vakalatina TEXT,
word_main_image TEXT,
word_main_audio TEXT,
story_audio TEXT,
)''';
static const String DELETE_TABLE = 'DROP TABLE IF EXISTS words';
}
//////////////////////////////WordTable SQLLITE END////////////////////////////////
class Word {
static String table = 'words';
int? WORD_ID;
String? TINA;
String? LETTER;
String? NABA;
String? ITAVI;
String? LOMANIBAI;
String? DEWA;
String? IVAKAMACALA;
String? COKE;
String? IDUSIDUSI;
String? LINKED_SYN;
String? IVOSAVOSA;
String? ITAKATAKA;
String? VOSA_VAKALATINA;
String? WORDIMG;
String? MAIN_AUDIO;
String? STORY_AUDIO;
Word(
{this.WORD_ID,
this.TINA,
this.LETTER,
this.NABA,
this.ITAVI,
this.LOMANIBAI,
this.DEWA,
this.IVAKAMACALA,
this.COKE,
this.IDUSIDUSI,
this.LINKED_SYN,
this.IVOSAVOSA,
this.ITAKATAKA,
this.VOSA_VAKALATINA,
this.WORDIMG,
this.MAIN_AUDIO,
this.STORY_AUDIO});
factory Word.fromJson(Map<String, dynamic> json, String lang) {
return Word(
WORD_ID: json['word_id'] ?? "0",
TINA: json['tina'] ?? "",
LETTER: json['letter'] ?? "",
NABA: json['naba'] ?? "0",
ITAVI: json['itavi'] ?? "0",
LOMANIBAI: json['lomanibai'] ?? "",
DEWA: json['dewa'] ?? "",
IVAKAMACALA: json['ivakamacala'] ?? "No Description Provided",
COKE: json['coke'] ?? "",
IDUSIDUSI: json['idusidusi'] ?? "",
IVOSAVOSA: json['ivosavosa'] ?? "",
ITAKATAKA: json['itakataka'] ?? "",
VOSA_VAKALATINA: json['vosa_vakalatina'] ?? "",
WORDIMG: json['word_main_image'] ?? "",
MAIN_AUDIO: json['word_main_audio'] ?? "",
STORY_AUDIO: json['story_audio'] ?? "");
}
}
The query in plantTableQuery is incomplete:
INSERT INTO words (
...
word_main_audio,
story_audio,
VALUES (
'${words.WORD_ID}',
'${words.TINA}',
... ```
SQLite has diagrams on their website that show the syntax of commands. They show you that in a CREATE TABLE query:
the column-names should be enclosed in brackets (you don't have a closing bracket ))
there are commas between column-names, but there can't be one before the closing bracket ).
The CREATE TABLE diagram shows you that the query in variable CREATE_TABLE may not have a comma before the closing bracket ) that encloses the column-defs, either:
...
word_main_audio TEXT,
story_audio TEXT,
)
You have a syntax error in your INSERT query near values.
Insert should be in this format
INSERT INTO table (column1,column2 ,..)
VALUES( value1, value2 ,...);
You are missing closing brackets just after column story_audio.
static String plantTableQuery(WordTable words) {
return ''' INSERT INTO words (
word_id,
tina,
letter,
naba,
itavi,
lomanibai,
dewa,
ivakamacala,
coke,
idusidusi,
ivosavosa,
itakataka,
vosa_vakalatina,
word_main_image,
word_main_audio,
story_audio)
VALUES(
'${words.WORD_ID}',
'${words.TINA}',
'${words.LETTER}',
'${words.NABA}',
'${words.ITAVI}',
'${words.LOMANIBAI}',
'${words.DEWA}',
'${words.IVAKAMACALA}',
'${words.COKE}',
'${words.IDUSIDUSI}',
'${words.IVOSAVOSA}',
'${words.ITAKATAKA}',
'${words.VOSA_VAKALATINA}',
'${words.WORDIMG}',
'${words.MAIN_AUDIO}',
'${words.STORY_AUDIO}'
)''';
}
This is my code :
String text = snapshot.data[index];
var splitText = text.split("\n") ;
final jdata = jsonEncode(splitText[5]);
print(jdata);
which prints the String :
"RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}"
snapshot.data[index] contains :
I/flutter (14351): Code : LE-0000000002
I/flutter (14351): Description : test_01
I/flutter (14351): Organisation Unit : 01_01_04_01_SA - Shah Alam
I/flutter (14351): Date Reported : 18/09/2020
I/flutter (14351): Status : LE110 - Pending Approval
I/flutter (14351): RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}
my question is how do I access the value of "id".
Thanks!
I'm assuming that string is not changing in any condition other wise logic may fail..
void main() {
// actual string
// String x="RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}";
String x = snapshot.data[index];
// remove unwanted substring form string
List keyValues= x.replaceAll('RunHyperlink : {','').replaceAll('}','').replaceAll(', ',',').split(",");
//create map
Map map = {};
// run for loop to split key and value
for (var element in keyValues){
print(element.split(": ")[0]);
map.addAll({element.split(": ")[0] : element.split(": ")[1]});
}
// get the id balue
print(map['id']);
}
String temp;
const start = " id:";
const end = ",";
if (str.contains(start)) {
final startIndex = str.indexOf(start);
final endIndex = str.indexOf(end, startIndex + start.length);
temp = str.substring(startIndex + start.length, endIndex);
print("ID $temp");
}
or
Iterable<Match>? matches = RegExp(r' id\W*([a-z0-9\s]+,)').allMatches(str);
for (var m in matches) {
print(m.group(0));
}
I am building a Flutter app and have some trouble defining a model. I have model which has some properties. One of those properties can be both null or another model.
import 'package:proef/models/worked_time.dart';
class Shift {
String uuid;
DateTime start_at;
DateTime end_at;
String title;
String comment;
WorkedTime worked_time;
Shift(
{this.uuid,
this.start_at,
this.end_at,
this.title,
this.comment,
this.worked_time});
factory Shift.fromData(Map<String, dynamic> parsedJson) {
print(parsedJson);
return Shift(
uuid: parsedJson['uuid'],
start_at: DateTime.parse(parsedJson['start_at']).toLocal(),
end_at: DateTime.parse(parsedJson['end_at']).toLocal(),
title: parsedJson['title'],
comment: parsedJson['comment'],
worked_time: parsedJson['worked_time'] == null
? null
: parsedJson['worked_time']);
}
}
This does not work. When I use this model it throws me the following error:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'WorkedTime'
I am not sure how to fix this, since I am quite new to Dart and Flutter.
The WorkedTime model:
class WorkedTime {
String uuid;
String comment;
int status;
int took_break;
DateTime start_at;
DateTime end_at;
WorkedTime({
this.uuid,
this.comment,
this.status,
this.took_break,
this.start_at,
this.end_at,
});
factory WorkedTime.fromData(Map<String, dynamic> parsedJson) {
print(parsedJson);
return WorkedTime(
uuid: parsedJson['uuid'],
comment: parsedJson['comment'],
status: parsedJson['status'],
took_break: parsedJson['took_break'],
start_at: DateTime.parse(parsedJson['start_at']),
end_at: DateTime.parse(parsedJson['end_at']));
}
}
The JSON with worked_time
[
{
"uuid": "706f40e7-d57c-470c-9023-b0c58e2c7c3a",
"start_at": "2020-09-01T08:00:00.000000Z",
"end_at": "2020-09-01T16:00:00.000000Z",
"title": "Test",
"comment": "Test",
"worked_time": {
"uuid": "6e73b4aa-d6e1-41f7-86cb-09745d2db033",
"comment": "Test",
"status": 0,
"break": 0,
"start_at": "2020-09-01T08:00:00.000000Z",
"end_at": "2020-09-01T16:00:00.000000Z",
"took_break": 0
}
}
]
The JSON without worked_time
[
{
"uuid": "706f40e7-d57c-470c-9023-b0c58e2c7c3a",
"start_at": "2020-09-01T08:00:00.000000Z",
"end_at": "2020-09-01T16:00:00.000000Z",
"title": "Test",
"comment": "Test",
"worked_time": null
}
]
Can you try this model
// To parse this JSON data, do
//
// final shift = shiftFromJson(jsonString);
import 'dart:convert';
List<Shift> shiftFromJson(String str) => List<Shift>.from(json.decode(str).map((x) => Shift.fromJson(x)));
String shiftToJson(List<Shift> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Shift {
Shift({
this.uuid,
this.startAt,
this.endAt,
this.title,
this.comment,
this.workedTime,
});
String uuid;
DateTime startAt;
DateTime endAt;
String title;
String comment;
WorkedTime workedTime;
factory Shift.fromJson(Map<String, dynamic> json) => Shift(
uuid: json["uuid"] == null ? null : json["uuid"],
startAt: json["start_at"] == null ? null : DateTime.parse(json["start_at"]),
endAt: json["end_at"] == null ? null : DateTime.parse(json["end_at"]),
title: json["title"] == null ? null : json["title"],
comment: json["comment"] == null ? null : json["comment"],
workedTime: json["worked_time"] == null ? null : WorkedTime.fromJson(json["worked_time"]),
);
Map<String, dynamic> toJson() => {
"uuid": uuid == null ? null : uuid,
"start_at": startAt == null ? null : startAt.toIso8601String(),
"end_at": endAt == null ? null : endAt.toIso8601String(),
"title": title == null ? null : title,
"comment": comment == null ? null : comment,
"worked_time": workedTime == null ? null : workedTime.toJson(),
};
}
class WorkedTime {
WorkedTime({
this.uuid,
this.comment,
this.status,
this.workedTimeBreak,
this.startAt,
this.endAt,
this.tookBreak,
});
String uuid;
String comment;
int status;
int workedTimeBreak;
DateTime startAt;
DateTime endAt;
int tookBreak;
factory WorkedTime.fromJson(Map<String, dynamic> json) => WorkedTime(
uuid: json["uuid"] == null ? null : json["uuid"],
comment: json["comment"] == null ? null : json["comment"],
status: json["status"] == null ? null : json["status"],
workedTimeBreak: json["break"] == null ? null : json["break"],
startAt: json["start_at"] == null ? null : DateTime.parse(json["start_at"]),
endAt: json["end_at"] == null ? null : DateTime.parse(json["end_at"]),
tookBreak: json["took_break"] == null ? null : json["took_break"],
);
Map<String, dynamic> toJson() => {
"uuid": uuid == null ? null : uuid,
"comment": comment == null ? null : comment,
"status": status == null ? null : status,
"break": workedTimeBreak == null ? null : workedTimeBreak,
"start_at": startAt == null ? null : startAt.toIso8601String(),
"end_at": endAt == null ? null : endAt.toIso8601String(),
"took_break": tookBreak == null ? null : tookBreak,
};
}
The compiler does not complain about assigning a dynamic variable to a typed variable because the check is done at runtime. Therefore, you can write:
void main() {
dynamic value = "something";
String string = value; // ok, value holds a String; runtime is fine
WorkedTime time = value; // evaluated at runtime; exception
}
This issue is present in Shift's factory constructor:
worked_time: parsedJson['worked_time'] == null
? null // true: can assign null to WorkedTime
: parsedJson['worked_time']); // false: assign dynamic to WorkedTime
You are attempting to assign a dynamic type with a value of parsedJson['worked_time'] to your WorkedTime type. These are incompatible types. Instead, you must use WorkedTime's constructor to construct the instance from the JSON map. Here is a minified example of your issue:
class WorkedTime {
String comment;
WorkedTime.fromData(Map<String, dynamic> json) : comment = json['comment'];
}
class Shift {
String uuid;
WorkedTime worked_time;
Shift.fromData(Map<String, dynamic> json)
: uuid = json['uuid'],
// next line causes the exception; cannot assign dynamic to WorkedTime
// fix: use WorkedTime.fromData(json['worked_time'])
worked_time = json['worked_time'];
}
In order to fix this, use WorkedTime.fromData(...)'s constructor.
class Shift {
String uuid;
WorkedTime worked_time;
Shift.fromData(Map<String, dynamic> json)
: uuid = json['uuid'],
worked_time = json['worked_time'] != null
? WorkedTime.fromData(json['worked_time']) // parse WorkedTime's json
: null;
}
void main() {
const json = <String, dynamic>{
'uuid': '706f40e7-d57c-470c-9023-b0c58e2c7c3a',
'worked_time': <String, dynamic>{'comment': 'on break'}
};
final shift = Shift.fromData(json);
// check that shift.worked_time is not null, etc.
print(shift.worked_time.comment);
}
i have an API that return data type of _HttpClientResponse cause i am using httpClient, i decode the result to string using the below
var reply = await memoryResponse.transform(utf8.decoder).join();
when i print the result
I/flutter (23708): String
I/flutter (23708): {"results":
[{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},
{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"}]}
then decode it with json.decod
var memJasonData = json.decode(reply);
when i print the runType
_InternalLinkedHashMap<String, dynamic>
{results:[{IPAddress": 192.1.1.1, Description: Windows 2016 Server},
{IPAddress: 192.1.1.1", Description : Windows 2016 Server },{ IPAddress :
192.1.1.1", Description : Windows 2016 Server }]}
i created a class to to be used here an i tried
List<Results> _getMemoryData1 = memJasonData.map((json) =>
Results.fromJson(json)).toList();
setState(() {
print(_getMemoryData1);
getMemoryData = _getMemoryData1;
print(getMemoryData);
also i tried to for lop after converting the map to list
var memToListData = memJasonData['results'] as List; '''
but nothing working with me
i appreciate your help
the function
''' var getMemoryData = const [];
Future _getMemoryData() async {
var url ='https://10.1.1.1/v3/Json/Query?query';
HttpClient client = new HttpClient();
client.addCredentials(Uri.parse(url), '10.1.1.1',
HttpClientBasicCredentials('user', 'pass'));
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
HttpClientRequest memoryRequest = await client.getUrl(Uri.parse(
'$url=SELECT+TOP+15+IPAddress,+Description,+DNS,+SysName,+Vendor,+Status,+Last Boot,+PercentMemoryUsed,+PercentMemoryAvailable,+MachineType, +TotalMemory+FROM+Orion.Nodes+ORDER+By+PercentMemoryUsed+DESC'));
memoryRequest.headers.set('content-type', 'application/json',);
HttpClientResponse memoryResponse = await memoryRequest.close();
var reply = await memoryResponse.transform(utf8.decoder).join();
var memJasonData = json.decode(reply);
// var memToListData = memJasonData['results'] as List;
List<Results> _getMemoryData1 = memJasonData.map((json) =>
Results.fromJson(json)).toList();
setState(() {
print(_getMemoryData1);
getMemoryData = _getMemoryData1;
print(getMemoryData);
});
// for (var v in memToListData){
// Results memResults = Results(v['iPAddress'], v['description'], v['dNS'], v['sysName'], v['vendor'], v['status'], v['lastBoot'], v['percentMemoryUsed'], v['percentMemoryAvailable'], v['machineType']);
// getMemoryData.add(memResults);
// }
// print(getMemoryData.length);
// print(getMemoryData.runtimeType);
// return getMemoryData;
} '''
class below
below is the class
class Results {
String iPAddress;
String description;
String dNS;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Results(
this.iPAddress,
this.description,
this.dNS,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
);
Results.fromJson(Map<String, dynamic> json) :
iPAddress = json['IPAddress'],
description = json['Description'],
dNS = json['DNS'],
sysName = json['SysName'],
vendor = json['Vendor'],
status = json['Status'],
lastBoot = json['LastBoot'],
percentMemoryUsed = json['PercentMemoryUsed'],
percentMemoryAvailable = json['PercentMemoryAvailable'],
machineType = json['MachineType'];
}
Error
type '(dynamic) => Results' is not a subtype of type '(String, dynamic) =>
MapEntry' of 'transform'
you can copy paste and run full code below
If your json look like this
{"results": [
{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server",
"DNS" : "",
"SysName" :"",
"Vendor":"",
"Status":12,
"LastBoot":"",
"PercentMemoryUsed":123,
"PercentMemoryAvailable": 456,
"MachineType":""
}, {"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server"}]}
code snippet for parse and print
Payload payload = payloadFromJson(jsonString);
print('${payload.results[0].ipAddress}');
related class
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Result> results;
Payload({
this.results,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
results: List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
String ipAddress;
String description;
String dns;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Result({
this.ipAddress,
this.description,
this.dns,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
ipAddress: json["IPAddress"],
description: json["Description"],
dns: json["DNS"] == null ? null : json["DNS"],
sysName: json["SysName"] == null ? null : json["SysName"],
vendor: json["Vendor"] == null ? null : json["Vendor"],
status: json["Status"] == null ? null : json["Status"],
lastBoot: json["LastBoot"] == null ? null : json["LastBoot"],
percentMemoryUsed: json["PercentMemoryUsed"] == null ? null : json["PercentMemoryUsed"],
percentMemoryAvailable: json["PercentMemoryAvailable"] == null ? null : json["PercentMemoryAvailable"],
machineType: json["MachineType"] == null ? null : json["MachineType"],
);
Map<String, dynamic> toJson() => {
"IPAddress": ipAddress,
"Description": description,
"DNS": dns == null ? null : dns,
"SysName": sysName == null ? null : sysName,
"Vendor": vendor == null ? null : vendor,
"Status": status == null ? null : status,
"LastBoot": lastBoot == null ? null : lastBoot,
"PercentMemoryUsed": percentMemoryUsed == null ? null : percentMemoryUsed,
"PercentMemoryAvailable": percentMemoryAvailable == null ? null : percentMemoryAvailable,
"MachineType": machineType == null ? null : machineType,
};
}
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
List<Result> results;
Payload({
this.results,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
String ipAddress;
String description;
String dns;
String sysName;
String vendor;
int status;
String lastBoot;
int percentMemoryUsed;
int percentMemoryAvailable;
String machineType;
Result({
this.ipAddress,
this.description,
this.dns,
this.sysName,
this.vendor,
this.status,
this.lastBoot,
this.percentMemoryUsed,
this.percentMemoryAvailable,
this.machineType,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
ipAddress: json["IPAddress"],
description: json["Description"],
dns: json["DNS"] == null ? null : json["DNS"],
sysName: json["SysName"] == null ? null : json["SysName"],
vendor: json["Vendor"] == null ? null : json["Vendor"],
status: json["Status"] == null ? null : json["Status"],
lastBoot: json["LastBoot"] == null ? null : json["LastBoot"],
percentMemoryUsed: json["PercentMemoryUsed"] == null
? null
: json["PercentMemoryUsed"],
percentMemoryAvailable: json["PercentMemoryAvailable"] == null
? null
: json["PercentMemoryAvailable"],
machineType: json["MachineType"] == null ? null : json["MachineType"],
);
Map<String, dynamic> toJson() => {
"IPAddress": ipAddress,
"Description": description,
"DNS": dns == null ? null : dns,
"SysName": sysName == null ? null : sysName,
"Vendor": vendor == null ? null : vendor,
"Status": status == null ? null : status,
"LastBoot": lastBoot == null ? null : lastBoot,
"PercentMemoryUsed":
percentMemoryUsed == null ? null : percentMemoryUsed,
"PercentMemoryAvailable":
percentMemoryAvailable == null ? null : percentMemoryAvailable,
"MachineType": machineType == null ? null : machineType,
};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonString = '''
{"results": [
{"IPAddress":"192.1.1.1",
"Description":"Windows 2016 Server",
"DNS" : "",
"SysName" :"",
"Vendor":"",
"Status":12,
"LastBoot":"",
"PercentMemoryUsed":123,
"PercentMemoryAvailable": 456,
"MachineType":""
}, {"IPAddress":"192.1.1.2","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.3",
"Description":"Windows 2016 Server"}]}
''';
void _incrementCounter() {
Payload payload = payloadFromJson(jsonString);
print('${payload.results[0].ipAddress}');
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Output
I/flutter ( 9422): 192.1.1.1