请求多个API并在SQLITE上存储多个表的最佳方法

时间:2019-06-17 11:01:32

标签: flutter dart dart-http

问题是:如何在sqlite上存储?我的意思是如何在2个表上存储2个API数据?

我有多个API可以在缓存中获取和存储数据。目前,我是一个接一个地做的,就像这样:

按钮按下():

 await HelperDatabase1().storeRegister(_url, tokens);
 await HelperDatabase1().storeEquipmentReg(_url, tokens);
...

这让我的应用程序变慢了...所以我决定采用@günter-zöchbauer的方式。 (https://stackoverflow.com/a/50028061/9139407)但是我不明白如何在SQLite上存储多个表。

storeAll()已使用Future.wait

void storeAll(String url, String token) async {
  final urlList = ['$url/nativeapi/v1.0/Register','$url/nativeapi/v1.0/EquipmentReg'];

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

  final List<dynamic> caches = responses.map((response) {
    print('store All: ${response.body}');
    return json.decode(response.body);
  }).toList();
}

打印效果很好

以下两种当前使用的方法 storeRegister()方法(获取数据并存储在本地

storeRegister(String url, String token) async {
    var db = await db1;
    Batch batch = db.batch();
    final response = await http.get(
      '$url/nativeapi/v1.0/Register',
      headers: {'Authorization': 'Bearer $token'},
    );
    final jsonResponse = json.decode(response.body);
    AssetRegister model = AssetRegister.fromJson(jsonResponse);
    int length = model.data.length;
    for (int i = 0; i < length; i++) {
      var data = DataRegister(
          i: model.data[i].i,
          d: model.data[i].d,
          c: model.data[i].c,
          u: model.data[i].u,
          p: model.data[i].p,
          a: model.data[i].a);
      batch.insert(
        'registerTable',
        data.toMap()
      );
    }
    await batch.commit();
  }

storeWquipmentReg()方法

  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 个答案:

没有答案