定义一个带参数的 Widget,然后在调用该 Widget 时,只传递需要的参数,其他参数则使用可选参数表示。
示例代码:
import 'package:flutter/material.dart';
class MyCustomButton extends StatelessWidget {
final String buttonText;
final VoidCallback onPressed;
// 可选参数
final Color? buttonColor;
final double? buttonWidth;
// 带默认值的可选参数
final bool isOutline;
final Color borderColor;
const MyCustomButton({
Key? key,
required this.buttonText,
required this.onPressed,
this.buttonColor,
this.buttonWidth,
this.isOutline = false,
this.borderColor = Colors.black,
}) : super(key: key);
Widget build(BuildContext context) {
return SizedBox(
width: buttonWidth ?? double.infinity,
child: ElevatedButton(
onPressed: onPressed,
child: Text(buttonText),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color?>(
buttonColor ?? Theme.of(context).primaryColor),
shape: MaterialStateProperty.all<OutlinedBorder?>(
isOutline ? RoundedRectangleBorder(
side: BorderSide(color: borderColor),
): null),
),
),
);
}
}
上述代码定义了一个MyCustomButton
组件,包含了一些必须的参数和一些可选的参数,并对可选参数设置了默认值。在 build
方法中,我们使用了buttonWidth ?? double.infinity
来设置按钮宽度,使用buttonColor ?? Theme.of(context).primaryColor
来设置按钮颜色,这些都是在组件调用时可能不传递的参数。
在使用时,我们只需要传递必需的buttonText
和onPressed
参数,而对于其他参数,我们可以不传递,或者按照需要传递。例如:
MyCustomButton(
buttonText: 'Confirm',
onPressed: () {},
),
MyCustomButton(
buttonText: 'Cancel',
onPressed: () {},
buttonColor: Colors.grey,
),
MyCustomButton(
buttonText: 'Delete',
onPressed: () {},
buttonWidth: 120.0,
isOutline: true,
borderColor: Colors.red,
),
在上述示例中,我们创建了三个不同的MyCustomButton
组件,其中第二个和第三个组件设置了部分可选参数。