未处理的异常:类型'String'不是类型'double'的子类型SQFlite

时间:2019-03-26 21:34:27

标签: dart flutter sqflite

我正在尝试使用SQFlite将一些JSON数据保存到本地数据库中。我正在尝试保存int id, String parkingSpot, double latitude, double longitude

保存时一切正常,但是,当尝试读取所有保存的数据时,出现以下异常:Unhandled Exception: type 'String' is not a subtype of type 'double'

它指向以下代码: maps.forEach((map) => spots.add(ParkingSpot.fromMap(map))); latitude = map[columnLatitude];

database_helpers.dart

// data model class
class ParkingSpot {

  int id;
  String parkingSpot;
  double latitude;
  double longitude;

  ParkingSpot();

  // convenience constructor to create a ParkingSpot object
  ParkingSpot.fromMap(Map<String, dynamic> map) {
    id = map[columnId];
    parkingSpot = map[columnParkingSpot];
    latitude = map[columnLatitude];
    longitude = map[columnlongitude];
  }

  // convenience method to create a Map from this ParkingSpot object
  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      columnParkingSpot: parkingSpot,
      columnLatitude: latitude,
      columnlongitude:longitude
    };
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }
}

class Databasehelper
...

Future<List<ParkingSpot>> queryAllParkingSpots() async {
    Database db = await database;
    List<Map> maps = await db.query(tableParkingSpots);

    if (maps.length > 0) {
      List<ParkingSpot> spots = [];
      maps.forEach((map) => spots.add(ParkingSpot.fromMap(map)));
      return spots;
    }
    return null;
  }

main.dart

  void _read() async {
    DatabaseHelper helper = DatabaseHelper.instance;
    final spots = await helper.queryAllParkingSpots();
    print(spots);
    if (spots != null) {
      spots.forEach((spot) {
        print('row ${spot.id}: ${spot.parkingSpot}');
      });
    }
  }

  _save(String spotName, lat, lng) async {
    if(lat != null && lng != null) {
      saved = true;
      ParkingSpot spot = ParkingSpot();
      // lat == double.parse(lat.toString());
      // lng == double.parse(lng.toString());
      spot.parkingSpot = spotName;
      spot.latitude = lat;
      spot.longitude = lng;
      DatabaseHelper helper = DatabaseHelper.instance;
      int id = await helper.insert(spot);
      print('inserted row: $id');
    } else {
      print('cannot insert it');
    }
  }

我曾尝试使用lat == double.parse(lat.toString());将双打转换为字符串,但这会引发相同的异常。

我似乎无法找到并解决问题。

1 个答案:

答案 0 :(得分:0)

您做的正确double.parse,您只需要在fromMap构造函数中完成。

latitude = map[columnLatitude] is String ? double.parse(map[columnLatitude]) : map[columnLatitude];
longitude = map[columnlongitude] is String ? double.parse(map[columnlongitude]) : map[columnlongitude];