'Unhandled Exception: type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import './cart.dart';
class OrderItem {
final String id;
final double amount;
final List<CartItem> products;
final DateTime dateTime;
OrderItem({
required this.id,
required this.amount,
required this.products,
required this.dateTime,
});
}
class Orders with ChangeNotifier {
List<OrderItem> _orders = [];
List<OrderItem> get orders {
return [..._orders];
}
The errored block( when I do if check to null, vscode says The operand can't be null, so the condition is always false. also, I get an error saying Unhandled Exception: type 'Null' is not a subtype of type 'Map<String, dynamic>' in typecast.
Future<void> fetchAndSetOrders() async {
final url =
Uri.https('shopapp-63-default-rtdb.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;
}
extractedData.forEach((orderId, orderData) {
loadedOrders.add(
OrderItem(
id: orderId,
amount: orderData['amount'],
dateTime: DateTime.parse(orderData['dateTime']),
products: (orderData['products'] as List<dynamic>)
.map((item) => CartItem(
id: item['id'],
title: item['title'],
quantity: item['quantity'],
price: item['price'],
))
.toList(),
),
);
});
_orders = loadedOrders;
notifyListeners();
}
Solution 1:[1]
I think you are using Flutter 2.0+ which has nullsafety.
Thus you can not check for a null
to a variable which you do not define nullable explicitly.
Try defining
final response = await http.get(url);
final extractedData = json.de...
as
final response? = await http.get(url);
final extractedData? = json....
to slove The operand can't be null, so the condition is always false
Then you can check null using ??
operator or with the if condition you are already using.
I don't know why null
is not a subtype of type Map<String, dynamic>
is occurring. Because your http.get(url)
should not return null
by any means.
Solution 2:[2]
try this method instead.
{
final response = await http.get(url);
final _data = json.decode(response.body);
if (_data != null) {
final extractedData = _data as Map<String, dynamic>;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user18520267 |
Solution 2 | Suraj Rao |