Flutter pin_code_fields ^7.4.0如何设置输入框边框为渐变色
pin_code_fields 7.4.0 渐变边框配置方案
- 该版本
pin_code_fields组件内置的PinTheme仅支持纯色边框配置,没有提供直接设置渐变色边框的开放参数,你当前代码中使用的activeColor、inactiveColor等边框属性仅接收纯色Color类型值,无法直接传入渐变参数实现效果。
可落地的替代实现方式
组件提供了customFieldBuilder入参,支持完全自定义单个验证码输入格的渲染逻辑,你可以通过这个字段实现渐变边框效果,不需要修改组件源码,也不会破坏原有的输入、焦点切换逻辑。
实现步骤:
- 将
PinTheme中自带的所有边框宽度设为0,关闭默认纯色边框,避免和自定义效果冲突 - 在
customFieldBuilder回调中根据当前输入格的选中、输入状态,自行构建带渐变边框的容器 - 内层嵌套容器承载输入的验证码文字,预留出渐变边框的宽度即可
完整示例代码:
child: PinCodeTextField( appContext: context, controller: _otpField, length: 6, onChanged: (value) { print(value); }, enableActiveFill: true, pinTheme: PinTheme( // 关闭组件自带的默认边框 borderWidth: 0, activeBorderWidth: 0, inactiveBorderWidth: 0, selectedBorderWidth: 0, shape: PinCodeFieldShape.box, borderRadius: BorderRadius.circular(5), fieldHeight: SDP.sdp(33), fieldWidth: SDP.sdp(38), activeFillColor: Colors.white, inactiveFillColor: Colors.white, selectedFillColor: Colors.white, ), // 自定义输入格实现渐变边框 customFieldBuilder: (context, index, pinValue, state) { // 判断当前格子状态:选中/已输入内容/未激活 final isSelected = index == state.selectedIndex; final hasInput = pinValue.length > index && pinValue[index].trim().isNotEmpty; return Container( height: SDP.sdp(33), width: SDP.sdp(38), decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), // 选中/已输入状态显示渐变边框,可自行替换渐变颜色、方向 gradient: isSelected || hasInput ? const LinearGradient( colors: [Color(0xFF4A90E2), Color(0xFF9B51E0)], begin: Alignment.topLeft, end: Alignment.bottomRight, ) : null, border: Border.all( color: isSelected || hasInput ? Colors.transparent : AppColors.grayishBlue, width: 1, ), ), // 内层容器承载输入内容,margin值即为渐变边框的宽度 child: Container( margin: const EdgeInsets.all(1.5), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(4), ), alignment: Alignment.center, child: Text( hasInput ? pinValue[index] : '', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600), ), ), ); }, )
- 你可以根据业务需求自由调整渐变配色、边框宽度、不同状态下的样式规则,如果需要所有输入框统一显示渐变边框,去掉状态判断逻辑,给所有Container统一加上gradient配置即可。
内容的提问来源于stack exchange,提问作者Thomas M
相关产品推荐
相关产品推荐

