如何从网络解析JSON数据并将其保存到Flutter SQFLite数据库?

时间:2019-06-18 08:15:25

标签: flutter dart

我能够从网络加载JSON数据并将其直接显示在ListView中,而无需将其缓存在数据库中,这意味着没有网络连接,我将无法再次加载列表。因此,作为Flutter的新手,我想找到一种将数据保存到数据库中以供离线支持的方法。

这是从网络查询城市的JSON解析方法:

 getCities() async {
 var id;
 var name;
 var code;
 var district;
 var population;
 var jsonData = await http.get(BASE_URL);

 List cities = json.decode(jsonData.body);
 debugPrint('Response is $cities');

 List<City> cityList = cities.map((map) => City.fromJson(map)).toList();
 for (var city in cityList) {
 id = city.cityId;
 name = city.cityName;
 code = city.countryCode;
 district = city.cityDistrict;
 population = city.cityPopulation;
 print('Name is $name. and Id is $id');


 City cityObject = City(cityId: id,
    cityName: name,
    countryCode: code,
    cityDistrict: district,
     cityPopulation: population);
 WorldCitiesDatabaseHelper().insertCities(cityObject);
 }

这是数据库中的插入功能

Future<void> insertCities(City city) async{
var database =  _database;

await database.insert(citiesTable, city.toJson(), conflictAlgorithm:
ConflictAlgorithm.replace);
}

这是我的PODO类模型

class City {
 String cityId;
 String cityName;
 String countryCode;
 String cityDistrict;
 String cityPopulation;

 City(
  {this.cityId,
  this.cityName,
  this.countryCode,
  this.cityDistrict,
  this.cityPopulation});

 City.fromJson(Map<String, dynamic> json) {
 cityId = json['id'];
 cityName = json['name'];
 countryCode = json['code'];
 cityDistrict = json['district'];
 cityPopulation = json['population'];
}

 Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (cityId != null) {
  data['id'] = cityId;
}
data['name'] = this.cityName;
data['code'] = this.countryCode;
data['district'] = this.cityDistrict;
data['population'] = this.cityPopulation;
return data;
 }
}

这是日志猫中的错误

2019-06-21 15:42:56.362 20889-21014/com.sirikye.world_cities I/flutter: Name 
is Zwickau. and Id is 3145
2019-06-21 15:42:56.362 20889-21014/com.sirikye.world_cities I/flutter: Name 
is Zwolle. and Id is 28
2019-06-21 15:42:56.362 20889-21014/com.sirikye.world_cities I/flutter: Name 
is Zytomyr. and Id is 3446
2019-06-21 15:42:56.362 20889-21014/com.sirikye.world_cities I/flutter: Name 
is [San Cristóbal de] la Laguna. and Id is 698
2019-06-21 15:42:56.365 20889-21014/com.sirikye.world_cities E/flutter: 
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: 
NoSuchMethodError: The method 'insert' was called on null.
Receiver: null
Tried calling: insert("cities", _LinkedHashMap len:5, conflictAlgorithm: 
Instance of 'ConflictAlgorithm')
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
#1      WorldCitiesDatabaseHelper.insertCities 
(package:Cities/database/world_cities_database_helper.dart:54:20)
<asynchronous suspension>
#2      getCities (package:Cities/home.dart:78:33)
<asynchronous suspension>
#3      HomePage.build.<anonymous closure> (package:Cities/home.dart:43:11)
#4      _InkResponseState._handleTap 
(package:flutter/src/material/ink_well.dart:511:14)

这是我来自API的JSON响应

[{"id":"1","name":"Kabul","code":"AFG","district":"Kabol","population":"1780000"}, 
{"id":"2","name":"Qandahar","code":"AFG","district":"Qandahar","population":"237500"},{"id":"3","name":"Herat","code":"AFG","district":"Herat","population":"186800"}]

1 个答案:

答案 0 :(得分:0)

  

1个呼叫api

Map result = await GetUserInfo.callApi("YOUR URL");
      if (result["errorCode"] == "0") {
        UserModel userModel = result["value"];
        String userName = userModel.name;
      } else {
        String error = result["msg"];
        print(error);
        isError = true;
      }
  

2个解析数据

class GetUserInfo{
  static Future callApi(String url) async {
    final response = await http.get(url, headers: Config.httpGetHeader);
    final statusCode = response.statusCode;
    try {
      if (statusCode == 200) {
        Map body = json.decode(response.body);
          List arrayList=body['array'];
           List<UserModel> categoryModelList =categories.map((c) => new UserModel.fromMap(c)).toList();
          return {
            'errorCode': "0",
            'value': categoryModelList,
          };

      } else {
        return {'errorCode': "-1", 'msg': "Status Code Error"};
      }
    } catch (e) {
      print(e);
      return {'errorCode': "-1", 'msg': "$e"};
    }
  }
}
  

3个用户模型

class UserModel {

var id,name,code,district,population

UserModel.fromMap(Map<String, dynamic> map) {
    id = map['id'];
    name = map['name'];
    code = map['code'];
    district = map['district'];
    population = map['population'];   } }