【问题标题】:How to fetch data without for-loop?如何在没有for循环的情况下获取数据?
【发布时间】:2019-09-02 19:31:44
【问题描述】:

这里我一一存储了值。 API 有 100 万条数据。响应时间为 3 秒存储缓存需要很多时间。

如何像选择插入查询一样添加一次所有数据?

storeDefCatMaster(String url,String token) async {
  final response = await http.get(
    '${url}/v1.0/DefCatMaster',
    headers: {'Authorization': 'Bearer ${token}'},
  );
  final jsonResponse = json.decode(response.body);
  DefCatMaster model = DefCatMaster.fromJson(jsonResponse);
  int length = model.data.length;

  for(int i=0; i<length; i++) {
    var data = DataDefCatMaster(
      deF_CAT_ID: model.data[i].deF_CAT_ID,
      description: model.data[i].description,
      in_use: model.data[i].in_use,
      sortOrder: model.data[i].sortOrder
    );
    await helper.insert(data);
  }
}

【问题讨论】:

标签: sqlite dart flutter async-await sqflite


【解决方案1】:

sqflite 提供了批量执行 api,可以减少本地代码和 dart 代码之间的来回,这可能会提高性能。

示例代码:

batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();

像这样批量插入:

batch = db.batch();
for(int i=0; i<length; i++) {
    var data = DataDefCatMaster(
      deF_CAT_ID: model.data[i].deF_CAT_ID,
      description: model.data[i].description,
      in_use: model.data[i].in_use,
      sortOrder: model.data[i].sortOrder
    );
    batch.insert('table_name', data);
  }
results = await batch.commit(); 
//or
//await batch.commit(noResult: true);
// if you dont want result, this will improve performance as well.

您仍将使用 for 循环,但使用上述代码时性能会好得多。

【讨论】:

  • 数据在 3 秒内来自服务器,但存储缓存时间为 10 分钟。我不知道为什么会这样
  • json 解析也可能是导致执行速度缓慢的罪魁祸首,无论如何,如果它是如此强烈,我建议在后台进行。无论如何,我建议的方法也会对此有所帮助。
  • 我做了这样的背景:之前我曾经喜欢这样:await storeCategoryDefect(_url, tokens); 现在我删除了等待。但我的 listView 数据丢失了
猜你喜欢
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 2021-01-29
相关资源
最近更新 更多