【发布时间】:2022-01-03 06:03:39
【问题描述】:
我正在尝试从 JSON 中获取双精度值,但出现此错误。请帮助我如何解决这个问题。我不知道我在哪里搞砸了。
以下是我的错误:
AsyncSnapshot(ConnectionState.done, null, type 'String' 不是 type 'double' 的子类型,#0 new Product.fromMap (package:purple_star/screens/Model/product_model.dart:48:18 )
获取产品。 (包:purple_star/screens/Services/product_services.dart:13:50)
MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
新的 _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:188:27)
新的 _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
新 List.of (dart:core-patch/array_patch.dart:50:28)
ListIterable.toList (dart:_internal/iterable.dart:213:44)
fetchProduct (package:purple_star/screens/Services/product_services.dart:13:65)
class Product {
Product({
required this.productId,
required this.title,
required this.made,
required this.productImageUrl,
required this.strains,
required this.price,
required this.productType,
});
final int productId;
final String title;
final String made;
final String productImageUrl;
final String strains;
final double price;
ProductType productType;
factory Product.fromMap(Map<String, dynamic> json)
=> Product(
productId: json["productId"] as int,
title: json["title"] as String,
made: json["made"] as String,
productImageUrl: json["productImageUrl"] as String,
strains: json["strains"] as String,
price: json["price"] as double,
productType: ProductType.fromJson(json["productType"]));
}
Future<List<Product>> fetchProduct() async {
var URL = Uri.parse('https://mocki.io/v1/74d9dc9d-e33a-4fd3-b358-328d07be6aed');
final response = await http.get(URL);
if (response.statusCode == 200) {
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
print(parsed);
return parsed.map<Product>((json) => Product.fromMap(json)).toList();
} else {
throw Exception('Failed to load Products');
}
}
提前致谢。
【问题讨论】:
-
试试
price: double.tryParse(json["price"])??0 -
请发布一些演示问题的示例数据。