The switch case expression type 'Type' must be a subtype of the switch expression type 'BankEvent'
301
Yeah finally I found the answer after a bit of research.It should be writtern as below
handleEvents(BankEvent bankEvent){
switch(bankEvent.runtimeType){
case FetchBanks:
break;
}
}
Author by
Jarin Rocks
Updated on January 04, 2023Comments
-
Jarin Rocks over 1 year
I am getting this error when I try to use switch case in dart. I have an abstract class and two classes extending it. See the code below
abstract class BankEvent{} class FetchBanks extends BankEvent{} class DeleteBank extends BankEvent{ final int bankId; DeleteBank(this.bankId); }
I have to make some implementations inside the handleEvents method depends on the instance of the class I am receiving as parameter. But I am getting the error (The switch case expression type 'Type' must be a subtype of the switch expression type 'BankEvent') in the case statement of switch case. My code for the switch case implementation is below
handleEvents(BankEvent bankEvent){ switch(bankEvent){ case FetchBanks: break; } }
-
markspace about 2 yearsNot sure. At first pass,
FetchBanks
is of typeClass
, which might be causing the error. Try modify the switch in either respect and see if it removes the error. -
Jarin Rocks about 2 yearsI am not getting your point
-
markspace about 2 yearsFor example, in the switch statement, replace
switch(bankevent)
withswitch(bankevent.getClass())
. -
Michael Horn about 2 yearsIf you're looking for something similar to sealed classes in Kotlin or enums in Swift, you may be interested in the freezed package: pub.dev/packages/freezed. Otherwise, the if-else approach is the way to go
-
Jarin Rocks about 2 yearsIf else approach is working fine. But if there are many events then switch is the better way right. I will look in to freezed package.
-
-
Michael Horn about 2 yearsThat's javascript type checking - The dart way to check the type is
if (bankEvent is FetchBank) {...}
-
Jarin Rocks about 2 years@MichaelHorn stackoverflow.com/a/71529798/8192246
-
andrestascon about 2 yearsThanks for the info, the question had the java tag which disoriented me