I have initialised an otherwise empty list and want to check if that entry is true or null. Since I can't practically populate every entry first with false, I need to check if it is null or true.

List<bool> check = List<bool>();

Whether I use:

(check[index]) ? dothis : dothat;

or:

(check[index] != null) ? dothis : dothat;

they both throw a range error. Since I can't initialise it like

List<bool> check = [false,false,false,false,false forever and ever];

How can I solve this?


Solution 1: Prathik

Check if the index exists, before getting the value.

List<bool> check = List<bool>();

if(index <= (check.length - 1)) {
  (check[index]) ? dothis : dothat;
}

OR

(index < check.length) 
                       ? (check[index]) ? Colors.blue : Colors.red
                       // return default color
                       :  Colors.white

Something like this should work!


Solution 2: CopsOnRoad

List<bool> check = [];

if (check.length > index) { // you are safe to perform anything like check[index] }

Update:

color: check.length > index ? (check[index] ? Colors.blue : Colors.grey) : Colors.white

Update2:

Not sure why you said it's not working, I am giving you a build() method, you can try to comment out the other code, and see it working.

Widget build(BuildContext context) {
  var check = [true];
  int index = 5;

  return Scaffold(
    appBar: AppBar(),
    body: Container(
      width: 100,
      height: 100,
      color: check.length > index ? (check[index] ? Colors.blue : Colors.grey) : Colors.white,
    ),
  );
}


Solution 3: jamesdlin

Since I can't initialise it like

List<bool> check = [false,false,false,false,false forever and ever];

It sounds to me like you want a sparsely populated List. If so, just use a Map<int, T> instead of List<T>. Then check[index] will return null if the item hasn't been added yet:

var check = <int, bool>{};
...
(check[index] ?? false) ? dothis : dothat;

In the case of bool, it'd be even better to use a Set<int> and just check for presence instead of maintaining a separate bool value:

var checked = <int>{};
...
checked.contains(index) ? dothis : dothat;


Solution 4: Stuck

To make life less painful:

extension ListExt<T> on List<T> {
  T? getOrNull(int index) {
    return index < length && index >= 0 ? this[index] : null;
  }

  T? nextOrNull(int index) => getOrNull(index + 1);

  T? prevOrNull(int index) => getOrNull(index - 1);
}

Then you can do:

[1, 2].getOrNull(0) // ==> 1
[1, 2].getOrNull(1) // ==> 2
[1, 2].getOrNull(2) // ==> null
[1, 2].getOrNull(-1) // ==> null

[1, 2].nextOrNull(0) // => 2
[1, 2].nextOrNull(1) // => null
[1, 2].nextOrNull(10) // => null

[1, 2].prevOrNull(0) // => null
[1, 2].prevOrNull(1) // => 1
[1, 2].prevOrNull(10) // => null