I have the following code to filter a list from data to be shown in a listView:
child: FutureBuilder(
future: fetchPacientes('todo'),
builder: (context, snapshot) {
if (snapshot.hasData) {
var filteredList = snapshot.data;
print("a minusculas:"
_controller.text.toLowerCase());
filteredList = filteredList
.where((element) => (element.nombre
.toLowerCase()
.contains(
_controller.text.toLowerCase()) ||
element.NHC.toLowerCase().contains(
_controller.text.toLowerCase()) ||
element.apellidos.toLowerCase().contains(
_controller.text.toLowerCase())))
.toList();
But I am getting an error at point:
.where(...
This is the error output:
The method 'where' can't be unconditionally invoked because the receiver can be 'null'.
I am trying to migrate an old app to Null Safety, but I am not able to solve this issue. The proposed solution is to add a null check at filteredList!
but the error is not removed when doing that way
CodePudding user response:
That error means that the object on which the .
is applied (in this case, the filteredList
) can be null
, so it would throw an exception if filteredList
will be actually null
.
So, to avoid the error, you have these options:
- Add a
!
afterfilteredList
: in this case, you're assuring the compiler thatfilteredList
will never ever be null, and the error will disappear. Note that this doesn't actually prevent it from beingnull
: you're just reassuring the compiler about it, andfilteredList
could still benull
. In that case, the app will throw a dedicated exception telling you that it found a 'null' object when you declared in the code that this should not have happened - Check if
filteredList
isnull
: add a few lines of code testing if it is reallynull
, and then handle the case, even something basic like returning aText('filteredList is empty')
. After this, you can safely writefilteredList!
because you are sure that it will never benull
, since you actually tested id. - Set a default value for
filteredList
in case it's null: Dart has this operator that assigns a value to an object if it isnull
:filteredList ??= []
. Again, after using this, you can safely writefilteredList!
because it will never be null.
PS sorry, didn't notice the last sentence. Since adding !
and a null
check isn't working, I'd try setting a default value for filteredList
. Or maybe checking for null
on snapshot.data
, and then set an explicit non-nullable type for filteredList
, like List<Object> filteredList
.
CodePudding user response:
The error is becausesnapshot.data
can be null
. Try adding a ?
before your .where
like so :
filteredList = filteredList?.where(...);