I wrote simple code to parse json data on flutter. An error occurs -
A value of type 'List<Null>' can't be assigned to a variable of type 'List<Office>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Office>'
My code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class OfficesList {
List<Office> offices;
OfficesList({required this.offices});
factory OfficesList.fromJson(Map<String, dynamic> json) {
var officesJson = json['offices'] as List;
List<Office> officesList = officesJson.map((element) {
Office.fromJson(element);
}).toList();
return OfficesList(
offices: officesList,
);
}
}
class Office {
final String name;
final String address;
final String image;
Office({required this.name, required this.address, required this.image});
factory Office.fromJson(Map<String, dynamic> json) {
return Office(
name: json['name'] as String,
address: json['address'] as String,
image: json['image'] as String,
);
}
}
Future<OfficesList> getOfficesList() async {
var url = "https://about.google/static/data/locations.json";
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return OfficesList.fromJson(json.decode(response.body));
} else {
throw Exception("Error: ${response.reasonPhrase}");
}
}
I tried adding "cast" to the problem line, but that didn't help. I am writing my code in Visual Studio code (if it matters). I'd be glad if you can help.
CodePudding user response:
The following code creates a new list with no type and all items being null, since you create a new office item, but do not return it from the map call:
List<Office> officesList = officesJson.map((element) {
Office.fromJson(element);
}).toList();
This is what you want, to create a List<Office>
List<Office> officesList = officesJson.map((element) {
return Office.fromJson(element);
}).toList();
or shorter:
var officesList = officesJson.map((json) => Office.fromJson(json)).toList();
CodePudding user response:
You should change the following since you are never returning anything:
List<Office> officesList = officesJson.map((element) {
Office.fromJson(element);
}).toList();
To:
List<Office> officesList = officesJson.map((element) {
return Office.fromJson(element);
}).toList();
Or do it shorter like this:
List<Office> officesList =
officesJson.map((element) => Office.fromJson(element)).toList();
Or even shorter if you are using Dart 2.15 or later:
List<Office> officesList = officesJson.map(Office.fromJson).toList();
And shortest (I think?):
List<Office> officesList = [...officesJson.map(Office.fromJson)];
