【问题标题】:type 'String' is not a subtype of type 'double' while converting from JSON从 JSON 转换时,“String”类型不是“double”类型的子类型
【发布时间】: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
  • 请发布一些演示问题的示例数据。

标签: json flutter dart


【解决方案1】:

在您的 JSON 文件中,“价格”的类型是 String 而不是 double。尝试用double.tryParse(json["price"])替换price: json["price"] as double

【讨论】:

  • 我以前试过这个,现在我添加了空检查,它现在可以工作了。感谢您的回复。
【解决方案2】:

试试下面的代码希望对你有帮助。

double.tryParse(json['price']),

或者试试下面的答案

您的 API 调用:

 Future<List<dynamic>> getInfoData() async {
    String url = 'https://mocki.io/v1/74d9dc9d-e33a-4fd3-b358-328d07be6aed';
    var response = await http.get(Uri.parse(url), headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    });
    return json.decode(response.body);
  }

您的小部件:

  Expanded(
        child: FutureBuilder<List<dynamic>>(
          future: getInfoData(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: snapshot.data!.length,
                  itemBuilder: (context, index) {
                    var name = snapshot.data![index]['title'];
                    var price = snapshot.data![index]['price'];
                    var productImageUrl =
                        snapshot.data![index]['productImageUrl'];
                    var made = snapshot.data![index]['made'];
                    var type1 =
                        snapshot.data![index]['productType']['type1'];
                    var type2 =
                        snapshot.data![index]['productType']['type2'];
                    var type3 =
                        snapshot.data![index]['productType']['type3'];

                    return Card(
                      shape: RoundedRectangleBorder(
                        side: BorderSide(color: Colors.green.shade300),
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                      child: ListTile(
                        title: Text(name),
                        subtitle: Text(
                          made + '\n' + type1 + '\n' + type2 + '\n' + type3,
                        ),
                        leading: Image.network(productImageUrl),
                        trailing: Text(price.toString()),
                      ),
                    );
                  },
                ),
              );
            }
            return Center(
              child: const CircularProgressIndicator(),
            );
          },
        ),
      ),

您的结果屏幕->

【讨论】:

  • 感谢 Ravindra 的建议。
猜你喜欢
  • 2020-10-30
  • 1970-01-01
  • 2021-11-07
  • 2021-12-12
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多