Home > Back-end >  check of myFinal == null don't work in flutter
check of myFinal == null don't work in flutter

Time:01-23

my Final declaration check if it's null don't work in flutter if (extractedData == null) { return; }

Future<void> fetchAndSetOrders() async {
    const url = 'https://flutter-update.firebaseio.com/orders.json';
    final response = await http.get(url);
    final List<OrderItem> loadedOrders = [];
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    if (extractedData == null) {
      return;
    }
  }

i try to look if if

extractedData == null

but flutter say that *The operand can't be null, so the condition is always true. *

CodePudding user response:

The error message you're seeing is likely because json.decode(response.body) will return null if the decoding fails, and extractedData is being assigned the result of this call. Therefore, extractedData is already guaranteed to be non-null when the if statement is executed.

One way to fix this would be to check for a null response before decoding the JSON:

if (response.body == null) {
  return;
}
final extractedData = json.decode(response.body) as Map<String, dynamic>;

Alternatively, you can check the value of the response status code, which will indicate whether the request was successful or not.

if (response.statusCode != 200) {
    return;
}
final extractedData = json.decode(response.body) as Map<String, dynamic>;

CodePudding user response:

You need to make extractedData nullable:

// Add the ? at the end
final extractedData = json.decode(response.body) as Map<String, dynamic>?;

CodePudding user response:

Actually you are giving extractedData variable data of type Map<String, dynamic> which will not be null-able and will throw error if json.decode() return a null value so if you wan to make it null-able change the

final extractedData = json.decode(response.body) as Map<String, dynamic>;

to this

final extractedData = json.decode(response.body) as Map<String, dynamic>?;

so the type of extractedData will be Map<String,dynamic>? which can also store null value and then you can use condition on it .

  • Related