我创建了两个按钮,但它们具有通用的构造函数参数。我不想再次编写相同的参数。我想从 mixin 或类中调用所有按钮的参数。我的按钮如下:
自定义文本按钮:
class HTextButton extends StatelessWidget { final TextStyle style; final Function() onPressed; final ButtonStyle? buttonStyle; final String title; const HTextButton(this.title,{Key? key, required this.onPressed, required this.style, this.buttonStyle}) : super(key: key); @override Widget build(BuildContext context) { return TextButton( style: buttonStyle, onPressed: onPressed, child: Text(title,style: style,)); } }
提交按钮:
class SubmitButton extends StatelessWidget { final TextStyle style; final Function()? onPressed; final Function()? onLongPressed; final ButtonStyle buttonStyle; final String title; const SubmitButton(this.title, {Key? key, required this.onPressed, required this.onLongPressed, required this.style, required this.buttonStyle}) : super(key: key); @override Widget build(BuildContext context) { return ElevatedButton( style: buttonStyle, child: Text(title, style: style), onPressed: onPressed, onLongPress: onLongPressed); } }
我创建了 mixin 来解决这个问题:
mixin ButtonFeatures {
late final TextStyle style;
late final Function() onPressed;
late final ButtonStyle? buttonStyle;
late final String title;
late final Function() onLongPressed;
}
这是我的自定义按钮的示例用法:
class HTextButton extends StatelessWidget with ButtonFeatures{
HTextButton(title,{Key? key, required onPressed, required style, buttonStyle}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
style: buttonStyle,
onPressed: onPressed, child: Text(title,style: style,));
}
}
如您所见,title 是一个字符串。但是当我使用如下按钮时,我没有收到任何错误:
HTextButton(12, onPressed: "aaaaa",)
我怎么解决这个问题 ?