Home > Enterprise >  Flutter: Check if multiple strings are empty or null while adding to array
Flutter: Check if multiple strings are empty or null while adding to array

Time:06-12

Still learning flutter, but have what I think is a pretty simple question. I have two strings, one being a list defined in the widget state.

List<String> uploadedFileUrls1;
String uploadedFileUrl2;

Each string is then either populated with uploaded media (images or video). These are then used to update a record in Firebase using arrayUnion as shown.

final postsUpdateData = {
  ...createPostsRecordData()
//this is where I need to check if empty or null
   'postAssets': FieldValue.arrayUnion(uploadedFileUrls1   [uploadedFileUrl2]),
 };
await columnPostsRecord.reference.update(postsUpdateData);

My question is, how do you check if either string is empty or null and not write to the database for that particular string. It is currently writing an empty string and I need it to do nothing, not even write a null, if the string is empty. But if one string is populated, I need it to add that one to the array but nothing for the empty one. Is setting new variables the only way to do this? Thanks for your help!

CodePudding user response:

You can just use the String.length and List.length method to check if either of the string is empty! So your code would look something like this:

 List<String> uploadedFileUrls1 = ['a', 'b', 'c'];
 String uploadedFileUrl2 = '';

  if (uploadedFileUrls1.length != 0 && uploadedFileUrl2.length != 0) {
    print('both has data');
    // process your update
  } else {
    print('no data');
    // notify user or do something 
  }

Hope this helps :D

CodePudding user response:

'postAssets': FieldValue.arrayUnion(uploadedFileUrls1.removeWhere((item) => ["", null].contains(item))   [uploadedFileUrl2]),

Try this

  • Related