Home > Mobile >  How to properly test response.body is null in Flutter?
How to properly test response.body is null in Flutter?

Time:03-31

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 []?

CodePudding user response:

Assuming that you're talking about Response from package:http, then Response.body is non-nullable and cannot be null.

It sounds like response.body is the literal string 'null'. That would be reasonable if you're expecting JSON. Ultimately your problem is that you are performing an unconditional cast (as List<dynamic>). json.decode returns a dynamic type and not a List or a Map precisely because it might return a different types of objects, so the proper fix is to just check first:

    var parsed = json.decode(response.body);
    if (parsed is List<dynamic>) {
      for (var matter in parsed) {
        matters.add(Matter.fromJson(matter));
      }
    }

and then you don't need to explicitly check for response.body being the string 'null' or for json.decode returning null.

  • Related