switch case 表达式类型“Type”;必须是 switch 表达式类型“BankEvent”的子类型;

发布于 2025-01-15 08:36:41 字数 540 浏览 0 评论 0原文

当我尝试在 dart 中使用 switch case 时,出现此错误。我有一个抽象类和两个扩展它的类。请参阅下面的代码,

abstract class BankEvent{}

class FetchBanks extends BankEvent{}

class DeleteBank extends BankEvent{
  final int bankId;
  DeleteBank(this.bankId);
}

我必须在 handleEvents 方法内进行一些实现,具体取决于我作为参数接收的类的实例。但我在 switch case 的 case 语句中收到错误(The switch case 表达式类型“Type”必须是 switch 表达式类型“BankEvent”的子类型)。我的 switch case 实现代码如下

handleEvents(BankEvent bankEvent){
    switch(bankEvent){
      case FetchBanks:
        break;
    }
  }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

起风了 2025-01-22 08:36:41

是的,经过一番研究,我终于找到了答案。它应该写成如下

handleEvents(BankEvent bankEvent){
    switch(bankEvent.runtimeType){
      case FetchBanks:
        break;
    }
  }

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;
    }
  }
夜夜流光相皎洁 2025-01-22 08:36:41

为什么不将 swith 更改为 if 语句,如下所示:

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

这有效并且非常易读。此外,您可以摆脱 switch 方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文