How to solve: type 'String' is not a subtype of type 'double' while converting from JSON

Question

Asked by Elam on January 03, 2022 (source).

I am trying to get the double value from JSON and i am getting this error. Please help me how to resolve this issue. I have no idea where i am messed up.

Below is my Error:

AsyncSnapshot<List>(ConnectionState.done, null, type 'String' is not a subtype of type 'double', #0 new Product.fromMap (package:purple_star/screens/Model/product_model.dart:48:18) fetchProduct. (package: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) new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:188:27) new _GrowableList.of (dart:core-patch/growable_array.dart:150:28) new 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');
  }
}

Thanks in advance.

Answer

Question answered by reza (source).

in your JSON file, the type of "price" is String not double. try to replace price: json["price"] as double with double.tryParse(json["price"])

DART FLUTTER JSON
SHARE: