likes
comments
collection
share

flutter中TextButton设置背景颜色

作者站长头像
站长
· 阅读数 27
根据文本框内容设置按钮不同背景颜色。

场景: 如登录,账号输入框还未输入任何账号时,下方的登录按钮应该置为灰色; 步骤:

  1. 设置按钮不同状态下的颜色,设置ButtonStylebackgroundColor属性为 createTextBtnBgColor()
  2. 设置按钮不可点击状态,将TextButtononPressed属性为null
var _amountChanged = false;
TextButton(
  style: ButtonStyle(backgroundColor: createTextBtnBgColor()),
  autofocus: false,
  onPressed: _amountChanged ? () {} : null,
  child: const Text(
    "确认提现",
    style: TextStyle(
      color: Colors.white,
    ),
  ),
)
2. 构建不同状态的背景颜色,这里用到了扩展函数

/// 处理点击按钮背景颜色
/// 设置当前按钮为不可点击时,设置onPressed回调为null。
MaterialStateProperty<Color> createTextBtnBgColor() {
  return MaterialStateProperty.resolveWith((states) {
// If the button is pressed, return green, otherwise blue
    if (states.contains(MaterialState.pressed)) { 
      return "#ff063c91".toColor();///扩展String函数
    } else if (states.contains(MaterialState.disabled)) {
      return "#509cf6".toColor();///扩展String函数
    }
    return "#FF208FF9".toColor(); ///扩展String函数
  });
}
3. 扩展String函数
extension String2Color on String {
  Color toColor() {
    final buffer = StringBuffer();
    if (length == 6 || length == 7) buffer.write('ff');
    buffer.write(replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }
}