使用super向父类传递必填参数失败的问题排查
Dart子类调用super传递参数报错解决
问题描述
子类调用super方法后无法将参数值传递给父类,编译时出现错误。
原代码
void main() { MobilePhone mp = new MobilePhone(modelName: "7T", brandName: "OnePlus"); } class Electronics { // 父类 double height = 56; double width = 56; double thickness = 56; Electronics({required String brandName}) { print("The Brand Name of this Mobile Phone is - $brandName"); } } class MobilePhone extends Electronics { // 子类 MobilePhone({required String modelName, required String brandName}) : super(brandName) { print("The model of this mobile phone is - $modelName"); } }
编译错误信息
main.dart:19:14: Error: Too many positional arguments: 0 allowed, but 1 found. Try removing the extra positional arguments. : super(brandName) {
错误原因
父类Electronics的构造函数使用了命名参数(参数被{}包裹),但子类调用super时,却以位置参数的形式传递brandName,违反了Dart的语法规则,因此触发报错。
解决方案
子类调用super时,必须以命名参数的形式传递参数,也就是在参数前加上参数名brandName:。
修正后的代码
void main() { MobilePhone mp = new MobilePhone(modelName: "7T", brandName: "OnePlus"); } class Electronics { double height = 56; double width = 56; double thickness = 56; Electronics({required String brandName}) { print("The Brand Name of this Mobile Phone is - $brandName"); } } class MobilePhone extends Electronics { MobilePhone({required String modelName, required String brandName}) : super(brandName: brandName) { // 修改为命名参数传递方式 print("The model of this mobile phone is - $modelName"); } }
运行修正后的代码,会正常输出:
The Brand Name of this Mobile Phone is - OnePlus The model of this mobile phone is - 7T
内容的提问来源于stack exchange,提问作者Rajiv Iyer
相关产品推荐
相关产品推荐

