skip to Main Content

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. *

2

Answers


  1. You need to make extractedData nullable:

    // Add the ? at the end
    final extractedData = json.decode(response.body) as Map<String, dynamic>?;
    
    Login or Signup to reply.
  2. 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 .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search