Warning: Operand of null-aware operation '??' has type 'int' which excludes null. _countries.indexWhere((country)
onTap: () {
int index =
_countries.indexWhere((country) {
return country.startsWith(
alphabet.toUpperCase());
}) ??
0;
_listController.jumpTo(
index * 60.0,
);
},
child: Text(
alphabet,
style: TextStyle(
color: _theme.primaryColor,
fontSize: 14.0,
fontWeight: FontWeight.bold,
),
),
CodePudding user response:
According to documentation, List.indexWhere
always returns int
- if the element isn't found, the return value is -1, but you seem to be thinking that it's null
.
CodePudding user response:
The documentation on indexWhere
clearly states:
Returns -1 if element is not found.
So there is no possible way that your call returns null
. The ??
operator only works on a nullable variable/expression, because it will return the result, or (in your case) 0
if the result is null
. The result can never be null
so your compiler tells you that that statement does not make any sense.
If you wanted the -1
to also be 0
, you could use min
to make sure the minimum you get is always 0
.
CodePudding user response:
indexWhere
doesn't return nullable int. You might want firstWhere
and then find index.
String item = _countries.firstWhere((country) {
return country.startsWith(alphabet.toUpperCase());
}, orElse: () => _countries.first);
int index = _countries.indexWhere((element) => element == item);
int selectedIndex = 0;
for (int i = 0; i < _countries.length; i ) {
if (_countries[i].startsWith(alphabet.toUpperCase())) {
selectedIndex = i;
break;
}
}
I hope there are better ways of doing it.