0

Is it possible to use loop inside query?

  Future<void> addServiceConfig(String uid, List<ServiceConfigModel> model) {
    _db.collection('users').document(uid).updateData({
      'businessDetails':{
        'serviceConfig':FieldValue.arrayUnion([
          {
            for(int i = 0;i <model.length;i++){
              if (model[i].inShop != null) 'inShop': model[i].inShop,
              if (model[i].inShopAndClientLocation != null)
                'inShopAndClientLocation': model[i].inShopAndClientLocation,
              if (model[i].clientLocation != null)
                'clientLocation': model[i].clientLocation,
              'serviceLocations': model[i].serviceLocations,
              'subCategoryId': model[i].subCategoryId
            }
        }
        ])
      }
    });
  }

I got this error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Invalid argument: Instance of '_CompactLinkedHashSet>'

1 Answer 1

1

You can't use a loop (or many other statements) inside an expression, like the value of a field. One solution is to pull construct the value outside of the update() all and then pass it in:

//var config = new Map()

var result = new List();

for(int i = 0;i < model.length; i++){
  var config = new Map();
  if (model[i].inShop != null) config['inShop'] = model[i].inShop;
  if (model[i].inShopAndClientLocation != null) 
    config['inShopAndClientLocation'] = model[i].inShopAndClientLocation;
  if (model[i].clientLocation != null) 
    config['clientLocation'] = model[i].clientLocation;
  config['serviceLocations'] = model[i].serviceLocations,
  config['subCategoryId'] = model[i].subCategoryId;
 result.add(config);
}

_db.collection('users').document(uid).updateData({
  'businessDetails':{
    'serviceConfig': FieldValue.arrayUnion(result)
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. I tried it. but only insert 1 value to database.. model length is 3. but insert only 1 to database
I think issue is, config variable is not a list of map

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.