Home > Back-end >  type 'String' is not a subtype of type 'double' while converting from JSON
type 'String' is not a subtype of type 'double' while converting from JSON

Time:01-03

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.

CodePudding user response:

Try below code hope its help to you.

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

Or try below answer

Your API call:

 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);
  }

Your Widget:

  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(),
            );
          },
        ),
      ),

Your Result screen-> enter image description here

CodePudding user response:

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"])

  • Related