I am new to dart and I am trying to create a basic inventory app with different types of chemicals.
I am trying to fetch data from firebase, which is getting back to me perfectly, but when I am trying to store it locally with a custom Model Class, its throwing me the following error
type 'int' is not a subtype of type 'String'
Here is the code for fetching and storing data locally
Future<void> getLoadedData() async {
final url = Uri.parse(
'https://inventory-db0eb-default-rtdb.asia-southeast1.firebasedatabase.app/chemicalList.json?auth=$authToken');
try {
final response = await http.get(url);
final List<ChemModel> _tempChemical = [];
final _tempChemList = json.decode(response.body) as Map<String, dynamic>;
_tempChemList.forEach((elementId, value) {
_tempChemical.add(
ChemModel(
id: ' ',
name: ' ',
// name: value['name'] ?? "Empty",
formula: ' ',
// formula: value['formula'] ?? "Empty",
description: ' ',
molWeight: double.parse(value['molWeight']),
// description: value['description'] ?? "Empty",)
),
);
});
_chemicalList = _tempChemical;
notifyListeners();
} catch (error) {
print(error);
rethrow;
}}
This is my model class
class ChemModel with ChangeNotifier {
String id;
String name;
String formula;
double molWeight;
String description;
ChemModel(
{required this.id,
required this.name,
required this.formula,
this.description = "",
this.molWeight = 0});
}
I'm not sure where I am going wrong.
CodePudding user response:
You can convert a value to double as follows
molWeight: value['molWeight'].toDouble(),
or
molWeight: (value['molWeight'] as int).toDouble(),
CodePudding user response:
model class may be a nuisance if you share a screenshot of the data source I can help more clearly
for exp :
I mean, the value from the data source is string, and if you're trying to keep it as a int in the model class, you might get this kind of error.