0

I'm running a query on an sqflite database in Futter and the async doesn't stop the code from jumping to the next code block.

    stateDetails.forEach(
      (state, region) async {
        await getRegionsInState(state).then(
          (regions) {
            regions.forEach(
              (region) {
                stateDetails[state][region] = {};
                print(stateDetails);
              },
            );
          },
        );
      },
    );

    print('adding regions');
    //Add Areas to Region
    stateDetails.forEach(
      (state, region) {
        region.forEach(
          (region, area) async {
            await getAreasInRegion(region).then(
              (areas) {
                areas.forEach(
                  (area) {
                    stateDetails[state][region][area] = [];
                  },
                );
              },
            );
          },
        );
      },
    );

The getRegionsInState() method is a query to the database which returns a list of values as shown in the output below.

I was expecting it to stop at the getRegionsInState(state).then() call on line 3, but it instead went on to the second block of code.

The output was:

I/flutter ( 3505): adding regions
I/flutter ( 3505): {Tasmania: {}}
I/flutter ( 3505): {Tasmania: {Islands: {}}}
I/flutter ( 3505): {Tasmania: {Islands: {}, North East: {}}}
I/flutter ( 3505): {Tasmania: {Islands: {}, North East: {}, North West: {}}}
I/flutter ( 3505): {Tasmania: {Islands: {}, North East: {}, North West: {}, South East: {}}}
I/flutter ( 3505): {Tasmania: {Islands: {}, North East: {}, North West: {}, South East: {}, South West: {}}}

Whereas it should be:

I/flutter ( 3505): {Tasmania: {}}
I/flutter ( 3505): {Tasmania: {Islands: {}}}
I/flutter ( 3505): {Tasmania: {Islands: {}, North East: {}}}
I/flutter ( 3505): {Tasmania: {Islands: {}, North East: {}, North West: {}}}
I/flutter ( 3505): {Tasmania: {Islands: {}, North East: {}, North West: {}, South East: {}}}
I/flutter ( 3505): {Tasmania: {Islands: {}, North East: {}, North West: {}, South East: {}, South West: {}}}
I/flutter ( 3505): adding regions
Levy77
  • 219
  • 1
  • 9
  • 1
    instead of `stateDetails.forEach` use `for(var detail in stateDetails) { ...` - do the same with `region.forEach` - adding `async` callback for `forEach` is not really a best idea... – pskink Dec 09 '20 at 15:40
  • Yeah this has worked, as it's a Map I used for(var detail in stateDetails.keys) { ... works fine tho thanks – Levy77 Dec 09 '20 at 16:04
  • 1
    yep, i missed it was `forEach(key, value)`... – pskink Dec 09 '20 at 16:12

0 Answers0