Flutter调用PostData构造函数提示参数未定义但已定义如何解决?
问题原因及修复方案
核心问题点
- 你定义的
PostData构造函数所有参数都是位置参数,但是调用时混合使用了title:、id:这类命名参数写法,Dart无法识别命名参数的键名,直接报参数未定义。 PostData构造函数参数列表未声明isPopular参数,但函数体内直接赋值this.isPopular = isPopular,同时调用时末尾传入的true没有对应参数位。- 调用
PostData时传入的name、token、image三个变量在当前fetchProducts方法作用域内没有定义,也会触发未定义报错。
修复步骤
- 调整
PostData构造函数定义,支持命名参数传值,补全缺失的isPopular参数:
// 简化构造函数写法,无需手动赋值this.xxx PostData( this.likesCount, this.likes, this.timestamp, this.postersName, this.postersId, this.postersImageUrl, this.postSavedByUsers, { required this.title, required this.id, required this.description, required this.price, required this.imageUrl, required this.productCategoryName, required this.brand, required this.isPopular, });
如果你不想用命名参数,就删除所有参数名前缀,所有参数按构造函数声明的顺序依次传入即可。
- 调整
fetchProducts里的PostData调用逻辑:
- 末尾的
true改为isPopular: true匹配命名参数 - 确认
name、token、image三个变量的来源,如果是存在Firestore文档中,改为element.get('对应字段名')获取,如果是全局变量确认作用域可访问。
修改后调用示例:
PostData( 0, [], Timestamp.now().millisecondsSinceEpoch, name, // 确保该变量已定义,或替换为element.get('postersName') token, // 确保该变量已定义,或替换为element.get('postersId') image, // 确保该变量已定义,或替换为element.get('postersImageUrl') [], title: element.get('productTitle'), id: element.get('productId'), description: element.get('productDescription'), price: double.parse(element.get('price')), imageUrl: element.get('productImage'), productCategoryName: element.get('productCategory'), brand: element.get('productBrand'), isPopular: true, )
内容的提问来源于stack exchange,提问作者Dijon
相关产品推荐
相关产品推荐

