I am facing this issue in my code and I am not able to solve it. I`m trying to fetch data through an API, and I get these errors in my IDE.
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'String'
#0 Products.fetchAndSetProducts.<anonymous closure> (package:shop_app/providers/products_provider.dart:85:28)
#1 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:400:8)
#2 Products.fetchAndSetProducts (package:shop_app/providers/products_provider.dart:81:21) <asynchronous suspension>
The errors above points at this function
Future<void> fetchAndSetProducts() async {
final url = Uri.parse(
'https://flutter-update-607c9-default-rtdb.firebaseio.com/products.json',
);
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final List<Product> loadedProducts = [];
extractedData.forEach((prodId, prodData) {
loadedProducts.add(
Product(
id: prodId,
title: prodData['title'],
description: prodData['description'],
price: prodData['price'],
isFavorite: prodData['isFavorite'],
imageUrl: prodData['imageUrl'],
),
);
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
rethrow;
}
}
And here is my Product class
class Product with ChangeNotifier {
final String? id;
final String title;
final String description;
final double price;
final String imageUrl;
bool isFavorite;
Product(
{required this.id,
required this.title,
required this.description,
required this.price,
required this.imageUrl,
this.isFavorite = false});
}
any help would be appreciated!