The switch case expression type 'Type' must be a subtype of the switch expression type 'BankEvent'
Asked Answered
C

2

2

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;
    }
  }
Concordant answered 18/3, 2022 at 15:22 Comment(5)
Not sure. At first pass, FetchBanks is of type Class, which might be causing the error. Try modify the switch in either respect and see if it removes the error.Hansiain
I am not getting your pointConcordant
For example, in the switch statement, replace switch(bankevent) with switch(bankevent.getClass()).Hansiain
If 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 goPediment
If 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.Concordant
C
4

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;
    }
  }
Concordant answered 18/3, 2022 at 15:55 Comment(0)
R
0

Why don't you just change your swith to an if statement, like so:

handleEvents(BankEvent bankEvent){ 
   if(bankEvent is FetchBank){
      // FetchBank stuff
   }else if(bankEvent is DeleteBank){
      // DeleteBank stuff
   }
}

This works and is quite readable. Besides, you can get rid off the switch approach.

Recoil answered 18/3, 2022 at 15:40 Comment(3)
That's javascript type checking - The dart way to check the type is if (bankEvent is FetchBank) {...}Pediment
@MichaelHorn https://mcmap.net/q/2033046/-the-switch-case-expression-type-39-type-39-must-be-a-subtype-of-the-switch-expression-type-39-bankevent-39Concordant
Thanks for the info, the question had the java tag which disoriented meRecoil

© 2022 - 2024 — McMap. All rights reserved.