type ‘Null’ can’t be assigned to CustomClass type

Viewed 37

I had been working after a long time with flutter and this new null safety is just breaking my code.

I had created a data model class to store values as an object as follows:

class MyClass{
  int x;
  String y;
  MyClass({this.x, this.y});
  .. .. ..rest of the code
}

Now in a provider I am having a list of MyClass objects to store data from the db. Over here I am using the firstWhere() to search for the required object by id.

MyClass getObj(int id){
   return list.firstWhere((obj) => obj.id == id, orElse: ()=>null);
}

But this keeps giving the error:

type ‘Null’ cant be assigned as it isn’t a subtype of MyClass

I tried firstWhereOrNull and also other solutions but to no avail.

2 Answers

You are trying to return null in non-nullable function. Try make MyClass nullable by adding? After MyClass like that

MyClass? getObj(int id){ return list.firstWhere((obj) => obj.id == id, orElse: ()=>null); }

The error message you're getting is because the return type of the orElse function must be non-nullable (in the docs, the signature is E and not E?).

If returning null from getObj is expected and you're prepared to handle that case elsewhere in code that calls getObj, then change the return type of the method to MyClass? (instead of MyClass) and use firstWhereOrNull, as you mentioned:

MyClass? getObj(int id){
  return list.firstWhereOrNull((obj) => obj.x == id);
}
Related