check list if it is empty or null flutter

1,303

when you try to use each item of an array and compare it to null, [null] and [] would have similar results. Instead, you should use .isEmpty because this method defines that is an array is empty or not, and in this approach [null] and []` are not equal because the first one has one element but the other one has 0 elements! For example:

//an example list
const list = [ [], [null]];
  
  for(int i=0; i<list.length; i++){
    if(list[i].isEmpty){
      print("empty " + i.toString());
    } else {
      print("not empty " + i.toString());
    }
  }

and the result will be:

empty 0
not empty 1

Similarly, you can use .length as follow:

const list = [ [], [null]];
for(int i=0; i<list.length; i++){
    print(i.toString() + " length is " + list[i].length.toString());
  }

These are only examples and you can map them to your code as well.

Share:
1,303
Admin
Author by

Admin

Updated on January 01, 2023

Comments

  • Admin
    Admin over 1 year

    I get this from the server, and I need to put my checkbox to true for values ​​with null, while I don't have to do anything if I find []

    {"FRI": [null], "MON": [null], "SAT": [null], "SUN": [{"to": "16:27", "from": "15:27"}], "THU": [null], "TUE": [null], "WED": []}
    

    I'm trying with a

    if (widget.initialValues!.every((e) => e == null)) {
      _isClosed.trigger(true);
    }
    

    but it does not work correctly because in both cases it returns to be true

    UPDATE

  • Admin
    Admin over 2 years
    mm ok, the examples are pretty clear to me, but in my code if I do an if (widget.initialValues! .isEmpty) it also takes me the values ​​with the null ..
  • Abbasihsn
    Abbasihsn over 2 years
    no, you should check element-wise not for entire initial values! because you want to be able to return true for each item that has [null] but in contrast do not want to have this feature for items with []. so you should check whole item separately
  • Admin
    Admin over 2 years
    mm ok i understand thanks, but I try to write your code but I have error.. I update my question with photo
  • Abbasihsn
    Abbasihsn over 2 years
    I think you are missing something, please provide the initialValue so I can check it out.