flutterdart

FormatException error when I change datatype from int to double (flutter)


Whenever I fetch the data from mysql server and parse it from json, error occurs and throws FormatException specifically on the price. but whenever I tried changing the price to int. it works properly. but since I'm working with prices, we all know that the data type should be double.

class Product {
      final int mid;
      final String icode;
      final String name;
      final String description;
      final double price;
      final int gid;
      final String gname;
      final String pic;
      int quantity;
    
      Product({
        required this.mid,
        required this.icode,
        required this.name,
        required this.description,
        required this.price,
        required this.gid,
        required this.gname,
        required this.pic,
        required this.quantity,
      });
    
      factory Product.fromJson(Map<String, dynamic> json) {
        return switch (json) {
          {
            'mid': int mid,
            'icode': String icode,
            'name': String name,
            'description': String description,
            'price': double price,
            'gid': int gid,
            'gname': String gname,
            'pic': String pic,
            'quantity': int quantity,
          } =>
            Product(
              mid: mid,
              icode: icode,
              name: name,
              description: description,
              price: price,
              gid: gid,
              gname: gname,
              pic: pic,
              quantity: quantity,
            ),
          _ => throw const FormatException('Failed to load Product.'),
        };
      }
    }

Solution

  • If the price is coming as an integer but you wish to make it double why not parse it?

    There could several ways but i suggest

    {
          'mid': int mid,
          'icode': String icode,
          'name': String name,
          'description': String description,
          'price': num? price, // could be anything (int, double or null)
          'gid': int gid,
          'gname': String gname,
          'pic': String pic,
          'quantity': int quantity,
        } =>
          Product(
            mid: mid,
            icode: icode,
            name: name,
            description: description,
            price: price?.toDouble() ?? 0.0, // if null add default value else make it double
            gid: gid,
            gname: gname,
            pic: pic,
            quantity: quantity,
          ),
    

    This way if price is null you get a default value while if it is int or double either way it will be converted to double.