【问题标题】:Unhandled Exception: type 'String' is not a subtype of type 'double' SQFlite未处理的异常:“String”类型不是“double”SQFlite 类型的子类型
【发布时间】:2019-03-26 21:34:27
【问题描述】:

我正在尝试使用 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()); 将双打转换为字符串,但这会引发相同的异常。

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

【问题讨论】:

    标签: dart flutter sqflite


    【解决方案1】:

    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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-11
      • 2021-09-19
      • 2021-07-18
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多