Flutter如何修改Date Picker组件内按钮的hover radius悬停圆角半径
Flutter Date Picker内部按钮悬停圆角半径修改方案
问题说明
Flutter 自带的Date Picker(日期选择器)组件默认内部按钮、日期单元格的悬停圆角半径过大,效果参考:
原有实现仅支持自定义组件颜色,无法调整悬停圆角参数,原有代码如下:
return Theme( data: Theme.of(context).copyWith( colorScheme: ColorScheme.light( primary: accentColor, // header background color onSecondary: colorSecondary, onPrimary: colorBlack, // header text color onSurface: colorBlack, // body text color ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( primary: colorBlack, // button text color ), ), ), child: Center( child: ConstrainedBox( constraints: BoxConstraints( maxWidth: Responsive.isMobile(context) ? MediaQuery.of(context).size.width : 500.0, maxHeight: Responsive.isMobile(context) ? MediaQuery.of(context).size.height : 490, ), child: child, ) ));
实现方法
组件支持修改悬停圆角半径,无需修改源码,通过主题覆盖即可实现,分两部分配置:
- 日期选择器内的日期单元格、年份选择项的形状(含hover状态圆角)通过
datePickerTheme配置 - 底部确定/取消等操作按钮的形状(含hover状态圆角)通过
textButtonTheme配置
修改后的完整代码如下,圆角值可根据需求自行替换:
return Theme( data: Theme.of(context).copyWith( colorScheme: ColorScheme.light( primary: accentColor, // 头部背景色 onSecondary: colorSecondary, onPrimary: colorBlack, // 头部文字颜色 onSurface: colorBlack, // 主体文字颜色 ), // 配置日期选择器内置元素样式 datePickerTheme: DatePickerThemeData( // 日期单元格形状,控制默认/悬停/选中状态的圆角 dayShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4), // 替换为你需要的圆角值 ), // 年份选择项形状 yearShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4), // 替换为你需要的圆角值 ), ), // 配置底部操作按钮样式 textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( primary: colorBlack, // 按钮文字颜色 // 按钮形状,控制默认/悬停/按压状态的圆角 shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4), // 替换为你需要的圆角值 ), ), ), ), child: Center( child: ConstrainedBox( constraints: BoxConstraints( maxWidth: Responsive.isMobile(context) ? MediaQuery.of(context).size.width : 500.0, maxHeight: Responsive.isMobile(context) ? MediaQuery.of(context).size.height : 490, ), child: child, ) ) );
进阶:单独配置hover状态圆角
如果需要区分hover状态和其他状态的圆角值(比如仅缩小hover状态的圆角,其他状态保持默认),可以使用MaterialStateProperty针对状态单独返回样式,以操作按钮为例:
textButtonTheme: TextButtonThemeData( style: ButtonStyle( foregroundColor: MaterialStateProperty.all(colorBlack), shape: MaterialStateProperty.resolveWith((states) { // 悬停状态下的圆角 if (states.contains(MaterialState.hovered)) { return RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)); } // 其余状态下的圆角 return RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)); }), ), )
日期单元格、年份项的差异化状态配置逻辑和上述按钮一致,在DatePickerThemeData对应的shape属性中使用MaterialStateProperty.resolveWith即可。
注:上述配置兼容Flutter 3.0及以上稳定版本,若使用更低版本,可升级SDK后使用该方案。
内容的提问来源于stack exchange,提问作者Viktor Vostrikov
相关产品推荐
相关产品推荐

