Search code examples
flutterdartdart-null-safety

How to deal with information that arrives null? - NoSuchMethodError


I'm getting null information from a web api. If a single information is null, the error will occur:

Error: Exception: NoSuchMethodError: '[]' Dynamic call of null. Receiver: null Arguments: ["address"]

I declared this information in the model like this:

final String? address;

..
address: json['data1']['data2'][0]['data3']['address'][0]

I tried to do something like:

address: json['data1']['data2'][0]['data3']['address'][0].isEmpty ? '' : json['data1']['data2'][0]['data3']['address'][0],

But it does not work.

I appreciate if anyone can help me analyze it!


Solution

  • The only thing you can do is to anticipate the null values and handle each case as needed.

    For instance, if a null value is not accepted at all, you could wrap the code in throw ... catch statement then throw an error -- e.g.Missing Data and handle that error.

    If having a null value is fine, you can use the null aware operator ? (or a nested if-statements if you prefer that). For example, assuming the value is a String, you could do something like this:

    final String? myValue = json['data1']?['data2']?[0]?['data3']?['address']?[0];
    

    Though, keep in mind if you're accessing a list by index, you still can get a RangeError if the index is out of range or if the list is empty. In such case you may need to split the process in a separate method and inspect each part separately such as:

    String? extractValue(Map<String, dynamic> json) {
      final firstList = json['data1']?['data2'];
      if (firstList is List && firstList.isNotEmpty) {
        final innerList = firstList[0]['data3']?['address'];
        if (innerList is List && innerList.isNotEmpty) {
          return innerList[0];
        }
      }
      return null; // or return a default value or throw an error
    }