Home > OS >  The switch case expression type 'Type' must be a subtype of the switch expression type �
The switch case expression type 'Type' must be a subtype of the switch expression type �

Time:03-19

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;
    }
  }

CodePudding user response:

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.

CodePudding user response:

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;
    }
  }
  • Related