87 lines
2.6 KiB
Dart
87 lines
2.6 KiB
Dart
// Assumiamo che le classi Coordinates e Row siano definite
|
|
// in file separati
|
|
import 'coordinates.dart';
|
|
import 'row.dart';
|
|
|
|
class Vineyard {
|
|
final int id;
|
|
final String name;
|
|
final String location;
|
|
final double hectares;
|
|
final Coordinates? coordinates;
|
|
final DateTime creationDate;
|
|
final List<Row>? rows;
|
|
final Map<int, Coordinates>? area;
|
|
|
|
// Costruttore con parametri nominati.
|
|
// 'rows' è opzionale perché è nullable.
|
|
Vineyard({
|
|
required this.id,
|
|
required this.name,
|
|
required this.location,
|
|
required this.hectares,
|
|
this.coordinates,
|
|
required this.creationDate,
|
|
this.rows,
|
|
this.area,
|
|
});
|
|
|
|
// ---
|
|
|
|
/// Converte l'oggetto Vineyard in una mappa per la serializzazione JSON.
|
|
Map<String, dynamic> toJson() {
|
|
return {
|
|
'id': id,
|
|
'name': name,
|
|
'location': location,
|
|
'hectares': hectares,
|
|
'coordinates': coordinates?.toJson(),
|
|
'creationDate': creationDate.toIso8601String(),
|
|
// Se 'rows' non è null, lo converte in una lista di mappe JSON
|
|
'rows': rows?.map((row) => row.toJson()).toList(),
|
|
// Converte la mappa 'area'
|
|
'area': area?.map((key, value) => MapEntry(key.toString(), value.toJson())),
|
|
};
|
|
}
|
|
|
|
/// Crea un oggetto Vineyard da una mappa (es. da una risposta JSON).
|
|
factory Vineyard.fromJson(Map<String, dynamic> json) {
|
|
try{
|
|
// Gestione della lista di 'rows'
|
|
final List<dynamic>? rowsJson = json['rows'];
|
|
final List<Row>? rowsList = rowsJson?.map((json) => Row.fromJson(json as Map<String, dynamic>)).toList();
|
|
|
|
// Gestione della mappa 'area'
|
|
final Map<dynamic, dynamic> areaJson = json['area'] as Map<dynamic, dynamic>;
|
|
final Map<int, Coordinates> areaMap = areaJson.map(
|
|
(key, value) => MapEntry(
|
|
int.parse(key as String), // Converte la chiave da String a int
|
|
Coordinates.fromJson(value as Map<String, dynamic>),
|
|
),
|
|
);
|
|
|
|
return Vineyard(
|
|
id: json['id'] as int,
|
|
name: json['name'] as String,
|
|
location: json['location'] as String,
|
|
hectares: (json['hectares'] as num).toDouble(),
|
|
coordinates: null,//Coordinates.fromJson(json['coordinates'] as Map<String, dynamic>),
|
|
creationDate: DateTime.parse(json['creationDate'] as String),
|
|
rows: rowsList,
|
|
area: areaMap,
|
|
);
|
|
} catch (e) {
|
|
print('Errore durante la deserializzazione dell\'oggetto Vineyard: $e');
|
|
return Vineyard(
|
|
id: 0,
|
|
name: '',
|
|
location: '',
|
|
hectares: 0.0,
|
|
coordinates: null,
|
|
creationDate: DateTime.now(),
|
|
rows: [],
|
|
area: {},
|
|
); // Restituisce un oggetto Vineyard vuoto in caso di errore
|
|
}
|
|
}
|
|
} |