Home > Software engineering >  Access first element of a nullable List<String> in Dart
Access first element of a nullable List<String> in Dart

Time:07-13

I'm loading a custom object 'selectedBox' from my server. Some Boxes don't have item images, then the property item_images has size = 0:

enter image description here

Now I need to access the first image (and display it to the user). If the box has no image, I want to show a default image:

String itemUrl = widget.selectedBox.item_images?[0] ??
    'https://enso-box.s3.eu-central-1.amazonaws.com/Allura - Park.png';

According to this question, I think this should work, but instead it throws an error when the selectedBox has no item images:

RangeError (index): Invalid value: Valid value range is empty: 0

Following works, but this can't be the best solution:

   List<String> itemImages = widget.selectedBox.item_images ??
    []; // first make sure that .item_images is not null
if (itemImages.length == 0) {
  itemImages = [
    'https://enso-box.s3.eu-central-1.amazonaws.com/Allura - Park.png'
  ];
}
log(itemImages[0])

CodePudding user response:

You can't access the first element of an empty list, and you get an error if you try. So you must not try. Using ?[0] doesn't work because the list is not null, it's just empty. It's precisely the same as [0] on the empty list.

The way to avoid that would be checking before accessing:

  log(itemImages.isNotEmpty ? itemImages.first : 'your-default-value')

If that's too long for you, you can use the firstOrNull from package:collection.

import "package:collection/collection.dart";
// ...
  log(itemImages.firstOrNull ?? 'your-default-value');
  • Related