Flutter获取MongoDB产品列表时int与double类型不兼容报错
类型不兼容错误:int与double互相转换失败
后端基于Node.js+Express搭建,数据存储在MongoDB中。POST请求提交产品时,客户端Dart的Product类与服务端Mongoose模型配合正常,无报错。但通过GET请求获取产品列表时,catch块抛出**"type int is not a subtype of type double"错误;尝试将Dart类中所有double类型改为int后,又出现"type double is not a subtype of type int"**错误。
GET 请求获取产品列表代码
Future<List<Product>> fetchAllProducts(BuildContext context) async { final userProvider = Provider.of<UserProvider>(context, listen: false); List<Product> productList = []; try { http.Response res = await http.get(Uri.parse('$uri/admin/get-products'), headers: { 'Content-Type': 'application/json; charset=UTF-8', 'x-auth-token': userProvider.user.token, }); httpErrorHandle( response: res, context: context, onSuccess: () { for (int i = 0; i < jsonDecode(res.body).length; i++) { productList.add( Product.fromJson( jsonEncode( jsonDecode(res.body)[i], ), ), ); print(' error in above .add block'); } }, ); } catch (e) { //error: type int is not a subtype of type double .. showSnackBar(context, e.toString()); } return productList; }
Dart Product 模型类
class Product { final String? id; final String name; final String description; final double price; final double quantity; final String category; final List<String> images; Product({ required this.name, required this.description, required this.price, required this.quantity, required this.category, required this.images, this.id, }); Map<String, dynamic> toMap() { return <String, dynamic>{ 'id': id, 'name': name, 'description': description, 'price': price, 'quantity': quantity, 'category': category, 'images': images, }; } factory Product.fromMap(Map<String, dynamic> map) { return Product( id: map['_id'], name: map['name'] ?? '', description: map['description'] ?? '', price: map['price'] ?? 0.0, quantity: map['quantity'] ?? 0.0, category: map['category'] ?? '', images: List<String>.from( (map['images']), )); } String toJson() => json.encode(toMap()); factory Product.fromJson(String source) => Product.fromMap(json.decode(source)); }
httpErrorHandle 工具函数
void httpErrorHandle({ required http.Response response, required BuildContext context, required VoidCallback onSuccess, }) { switch (response.statusCode) { case 200: onSuccess(); break; case 400: showSnackBar(context, jsonDecode(response.body)['msg']); break; case 500: showSnackBar(context, jsonDecode(response.body)['error']); break; default: showSnackBar(context, response.body); } }
内容的提问来源于stack exchange,提问作者mohitnx
相关产品推荐
相关产品推荐

