Flutter使用自定义CustomBtn报错:需4个位置参数,点击按钮无打印日志
问题原因
- 构造函数参数定义与调用不匹配:你定义的
CustomBtn构造函数中,write、onPressed、outlineBtn、isLoading四个参数都是必填位置参数,调用时必须按顺序传入,不能用命名参数(key: value)的形式传参,这就是报错"4 positional argument(s) expected, but 0 found"的直接原因。 - 参数名不匹配:你调用时传的参数是
text,但CustomBtn类中对应的文本属性名为write,参数名对应不上。 - 因为代码存在编译错误无法正常运行,所以点击按钮自然不会触发打印日志的逻辑。
解决方案(推荐写法,符合Flutter开发规范)
修改CustomBtn的构造函数,将参数改为命名参数,可按需设置默认值,避免后续调用传参出错:
import 'package:flutter/material.dart'; class CustomBtn extends StatelessWidget { // 如果你想用text作为参数名,直接把这里的write改成text即可 final String write; final void Function() onPressed; // 给非必填参数设置默认值 final bool outlineBtn; final bool isLoading; // 改造构造函数,参数用大括号包裹,必填参数加required const CustomBtn({ Key? key, required this.write, required this.onPressed, this.outlineBtn = false, this.isLoading = false, }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: onPressed, child: Container( height: 70.0, alignment: Alignment.center, decoration: BoxDecoration( border: Border.all( color: Colors.black, width: 2.0, ), borderRadius: BorderRadius.circular(12.0,), ), margin: const EdgeInsets.symmetric( horizontal: 24.0, vertical: 24.0, ), child: Text( write ?? "text", style: const TextStyle( fontSize: 16.0, color: Colors.black, fontWeight: FontWeight.w600, ), ), ), ); } }
修改后调整调用代码,把text改为write即可:
CustomBtn( write: "Create New Account", onPressed: () { print("Clicked"); }, ),
快速兼容方案(无需修改构造函数)
如果你不想改动CustomBtn的定义,直接按参数定义的顺序传入四个位置参数即可:
CustomBtn( "Create New Account", // 对应第一个参数write () { // 对应第二个参数onPressed print("Clicked"); }, false, // 对应第三个参数outlineBtn false, // 对应第四个参数isLoading ),
内容的提问来源于stack exchange,提问作者Bhavya Goel
相关产品推荐
相关产品推荐

