如何在SQFLITE多个表中存储多个API数据

时间:2019-06-19 06:39:59

标签: flutter dart dart-http

目前,我一个接一个地存储数据(调用一个API并存储一个表)。这减慢了我的申请速度。  我需要一次调用所有API,并一次存储sqflite多个表。因此,我搜索了google,发现了Future.wait

Future.wait()代码如下:

void storeAll(String url, String token) async {
  final urlList = ['$url/nativeapi/v1.0/Register','$url/nativeapi/v1.0/EquipmentReg'];//I have more than 15 APIs like this

  final responses = await Future.wait(
    urlList.map((String url) {
      return http.get(url,headers: {'Authorization': 'Bearer $token'});
    }),
  );

  final List<dynamic> caches = responses.map((response) {
    return json.decode(response.body);
  }).toList();
}

问题是如何将这些API数据存储在多个表中。

我的旧代码下方 //it's working well. but times is 2minutes

onPressed: () async {
    //delete existing tables--I deleted 15 tables like this
    await HelperDatabase1().deleteAssetAssembly();
    await HelperDatabase1().deleteEquipmentReg();
    //insert data after delete--I inserted 15 APIs to local like this
    await HelperDatabase1().storeEquipmentReg(_url, tokens);
    await HelperDatabase1().storeAssetAssembly(_url, tokens);
}

HelperDatabase1()。storeEquipmentReg(_url,令牌)函数

  Future<void> storeEquipmentReg(String url, String token) async {
    var db = await db1;
    Batch batch = db.batch();
    final response = await http.get(
      '${url}/nativeapi/v1.0/EquipmentReg',
      headers: {'Authorization': 'Bearer ${token}'},
    );
    final jsonResponse = json.decode(response.body);
    Assets model = Assets.fromJson(jsonResponse);
    int length = model.data.length;
    for (int i = 0; i < length; i++) {
      var data = DataEquipmentReg(
        i: model.data[i].i,
        r: model.data[i].r,
        l: model.data[i].l,
        t: model.data[i].t,
        p: model.data[i].p,
        c: model.data[i].c,
        u: model.data[i].u,
        a: model.data[i].a,
        b: model.data[i].b,
        eq_no: model.data[i].eq_no,
        isH_wit_C: model.data[i].isH_wit_C,
        n: model.data[i].n,
      );
      batch.insert(
        'EquipmentRegTable',
        data.toMap()
      );
    }
    await batch.commit();
  }

0 个答案:

没有答案