I am trying to understand how to work with Json in Flutter/Dart.
I want to read a local Json from the assets folder and display it on the screen.
I have in the assets folder the following Json
{
"title": [
{
"number": 8,
"firstarray": [
26.6, 27, 26.6, 22.9, 27.1, 26.8,
],
"secondarray": [
26.6, 27, 26.6, 22.9, 27.1, 26.8,
]
},
{
"number": 9,
"firstarray": [
26.6, 27, 26.6, 22.9, 27.1, 26.8,
],
"secondarray": [
26.6, 27, 26.6, 22.9, 27.1, 26.8,
]
}
]
}
I tried to created a Class "DataModel" to be able to read from JSON file.
class DataModel {
DataModel({this.measure});
List<DataTitle>? measure;
factory DataModel.fromJson(Map<String, dynamic> json) {
return DataModel(
measure: List<DataTitle>.from(
json['title'].map((c) => DataTitle.fromJson(c)).toList()),
);
}
}
class DataTitle {
DataTitle(
{required this.number,
required this.firstarray,
required this.secondarray});
int? number;
List<double>? firstarray;
List<double>? secondarray;
DataTitle.fromJson(Map<String, dynamic> json) {
number = json['number'];
firstarray = json['firstarray'] == null
? []
: List<double>.from(json['firstarray'].map((x) => x.toDouble()));
secondarray = json['secondarray'] == null
? []
: List<double>.from(json['secondarray'].map((x) => x.toDouble()));
}
}
and I am trying to read and print to the console as follows.
Future loadData() async {
String jsonString = await _loadData();
final jsonResponse = json.decode(jsonString);
DataTitle measure = DataTitle.fromJson(jsonResponse);
print('${measure.number} - ${measure.firstarray} - ${measure.secondarray}');
}
I get at the console printed out,
flutter: null - [] - []
but i was expecting
flutter: 8 - 26.6, 27, 26.6, 22.9, 27.1, 26.8 - 26.6, 27, 26.6, 22.9, 27.1, 26.8,