Home > Software engineering >  check list if it is empty or null flutter
check list if it is empty or null flutter

Time:09-30

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

CodePudding user response:

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.

CodePudding user response:

sorry if I reply to you with another account but I am at home with another pc and I do not have a user, I hope you will read ..

      final List<OpeningHours?>? initialValues;

class OpeningHours {
  OpeningHours({
    required this.open,
    required this.close,
  }) : assert(
          open.isBefore(close),
          "L'apertura dev'essere per forza prima della chiusura",
        );

  factory OpeningHours.fromMap(Map map) {
    if (!map.containsKey('from') || !map.containsKey('to')) {
      final msg =
          'La mappa $map non è valida per creare un oggetto [OpeningTime]';
      throw Exception(msg);
    }
    final from = TimeOfDayExtension.parse(map['from']! as String);
    final to = TimeOfDayExtension.parse(map['to']! as String);
    return OpeningHours(open: from, close: to);
  }

  final TimeOfDay open;

  final TimeOfDay close;

  String get format => '${open.asString()}-${close.asString()}';

  @override
  String toString() => jsonEncode(toMap());

  Map<String, String> toMap() =>
      {'from': open.asString(), 'to': close.asString()};
}
  • Related