1

问题是:如何在 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();
  }
4

0 回答 0