In my Flutter API I a getting an error
flutter: type 'Null' is not a subtype of type 'List' in type cast
when the response json list is empty. My API is written in Go. log.Println(mattersJSON) returns [1111 2222 3333 4444] and fmt.Println(string(mattersJSON)) returns null. This is expected as the query returns no records.
In Flutter, I have this code in my Api:
Future<List<Matter>> getMatters(BuildContext context) async {
List<Matter> matters = [];
try {
final response = await _helper.get(context, "/matters");
if (response.statusCode == 200) {
print(response.body);
if (response.body == null) {
return [];
}
print(response.body.length);
print('skipped test');
var parsed = json.decode(response.body) as List<dynamic>;
for (var matter in parsed) {
matters.add(Matter.fromJson(matter));
}
} else {
Navigator.pushNamed(context, RoutePaths.login);
return matters;
}
} catch (e) {
print(e);
return matters;
}
return matters;
}
The output is this:
flutter: null flutter: 4 flutter: skipped test flutter: type 'Null' is not a subtype of type 'List' in type cast
I'm tempted to assume that an empty response.body list will always have a length of 4 and that a response.body with records will always have have a length greater than 4. If so, then I could just test for a response.body.length > 4. However this is not elegant and probably fragile. I'm concerned that the error I'm seeing says the list is null and print(response.body) returns null but the response.body is not null.
How can I properly test for an empty response list and return []?