如何修改Flutter中TimePicker输入框的填充颜色?
解决Flutter showTimePicker输入框填充颜色修改问题
要修改时间选择器输入框的填充颜色,你需要针对输入框的InputDecorationTheme进行配置,之前的方案未覆盖到这部分样式,所以没有生效。以下是两种可行的解决方式:
方式一:全局主题配置
在你的全局ThemeData的TimePickerThemeData中添加inputDecorationTheme配置,直接全局生效:
timePickerTheme: TimePickerThemeData( backgroundColor: calculatedPrimaryColor, dialHandColor: calculatedSecondaryColor, dayPeriodColor: calculatedSecondaryColor .withOpacity(mode == ThemeMode.light ? .3 : .5), dayPeriodTextColor: calculatedInputColor, // 新增输入框样式配置 inputDecorationTheme: InputDecorationTheme( fillColor: Colors.yellow, // 设置你想要的填充颜色 filled: true, // 必须设置为true才会显示填充色 // 可选:调整输入框边框样式 focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.green), borderRadius: BorderRadius.circular(8), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey.shade300), borderRadius: BorderRadius.circular(8), ), ), ),
方式二:局部修改(仅当前时间选择器生效)
在showTimePicker的builder回调中,通过Theme.copyWith覆盖时间选择器的主题配置:
import 'package:flutter/material.dart'; Future<TimeOfDay?> showCustomTimePicker({ required BuildContext context, required TimeOfDay initialTime, }) async { return await showTimePicker( context: context, initialTime: initialTime, builder: (context, child) { return Theme( data: Theme.of(context).copyWith( colorScheme: Theme.of(context).colorScheme.copyWith( primary: Theme.of(context).colorScheme.secondary, ), // 覆盖时间选择器的输入框样式 timePickerTheme: Theme.of(context).timePickerTheme.copyWith( inputDecorationTheme: InputDecorationTheme( fillColor: Colors.blue, // 自定义填充色 filled: true, focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Theme.of(context).colorScheme.secondary), borderRadius: BorderRadius.circular(4), ), ), ), ), child: child!, ); }, ); }
关键说明
- 输入框的填充色由
InputDecorationTheme.fillColor控制,且必须设置filled: true才会生效; - 之前修改
colorScheme.primary仅会影响时间选择器的按钮、选中文字等元素,不会改变输入框的填充色; - 如果使用Material3,部分样式属性可能略有差异,但上述配置在Material2和Material3中均兼容。
内容的提问来源于stack exchange,提问作者dipansh
相关产品推荐
相关产品推荐

