1

I fetched data from API. storing data is very slow because inside my for loop insert data. How to create its instance before for loop or in class level?

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

  for(int i=0; i<length; i++) {
    var data = DataWoDescription(
      i: model.data[i].i,
      d: model.data[i].d,
      e: model.data[i].e,
      w: model.data[i].w,
      a: model.data[i].a,
      r: model.data[i].r,
      t: model.data[i].t,
      du: model.data[i].du,
      s: model.data[i].s,
      ra: model.data[i].ra,
      cul: model.data[i].cul,
    );
    await HelperDefCatMaster().insertWoDescription(data);
  }
}
0

1 Answer 1

1

This should be a better way to instantiate your database helper.

var helper;

void main() async {
  helper = await HelperDefCatMaster(); // instantiate it just once and use it everywhere. 
}

storeWoDescription(String url, String token) async {

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

  for (int i = 0; i < length; i++) {
    var data = DataWoDescription(
      i: model.data[i].i,
      d: model.data[i].d,
      e: model.data[i].e,
      w: model.data[i].w,
      a: model.data[i].a,
      r: model.data[i].r,
      t: model.data[i].t,
      du: model.data[i].du,
      s: model.data[i].s,
      ra: model.data[i].ra,
      cul: model.data[i].cul,
    );
    await helper.insertWoDescription(data);
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

I added helper in my main method, but when using await helper.insertWoDescription(data); in function helper is null
after click button i called function like this: await HelperDefCatMaster().deleteWoDescription(); await storeWoDescription(_url,tokens); Is it correct way?
still slow. why is that
First, the helper should not be null for sure. I don't know how you did that and did you miss something. Second, the solution I posted is a good practice of initialising database, so don't use your 2nd comment. Don't instantiate it in for loop, don't use HelperDefCatMaster() everywhere. It should be just one time call.
where do I call this function? storeWoDescription()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.