Flutter 定义公用组件,组件内传值分必填、可选和默认三部分

定义一个带参数的 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来设置按钮颜色,这些都是在组件调用时可能不传递的参数。

在使用时,我们只需要传递必需的buttonTextonPressed参数,而对于其他参数,我们可以不传递,或者按照需要传递。例如:

MyCustomButton(
  buttonText: 'Confirm',
  onPressed: () {},
),

MyCustomButton(
  buttonText: 'Cancel',
  onPressed: () {},
  buttonColor: Colors.grey,
),

MyCustomButton(
  buttonText: 'Delete',
  onPressed: () {},
  buttonWidth: 120.0,
  isOutline: true,
  borderColor: Colors.red,
),

在上述示例中,我们创建了三个不同的MyCustomButton组件,其中第二个和第三个组件设置了部分可选参数。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值