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;
    }
  }
Share:
301
Jarin Rocks
Author by

Jarin Rocks

Updated on January 04, 2023

Comments

  • Jarin Rocks
    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
      markspace about 2 years
      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.
    • Jarin Rocks
      Jarin Rocks about 2 years
      I am not getting your point
    • markspace
      markspace about 2 years
      For example, in the switch statement, replace switch(bankevent) with switch(bankevent.getClass()).
    • Michael Horn
      Michael Horn about 2 years
      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 go
    • Jarin Rocks
      Jarin Rocks about 2 years
      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.
  • Michael Horn
    Michael Horn about 2 years
    That's javascript type checking - The dart way to check the type is if (bankEvent is FetchBank) {...}
  • Jarin Rocks
    Jarin Rocks about 2 years
  • andrestascon
    andrestascon about 2 years
    Thanks for the info, the question had the java tag which disoriented me