我们在前面间章回中介绍过TimePicker,如果有看官忘记的话,可以点击这里查看。不过它的样式和内容都是固定的,无法修改,因此我们准备自定义一个TimePicker
组件,该组件只能选择小时和分钟,而且界面比较简洁,详细如下图所示。本章回中将介绍如何实现这种TimePicker组件。037
我们把效果图中的组件拆分成四个小组件:
Stack(
children: [
///深色方框用来显示当前被选择的数字
Positioned(
///这个值是listHeight的值除2后再做一些偏移
top: (screenHeight*2/3 - 128)/2 -26,
// top: 300,
///这个16是左右的边距
left: 16,
width: screenWidth-16*2,
height: 56,
child:Container(
decoration: BoxDecoration(
color: Colors.blue[500],
borderRadius: BorderRadius.circular(24),
),
),
),
///数字选择:使用两个滑轮实现
Positioned(
top: 0,
///这个值是屏幕宽度减去两个listWidth和sizeBox的宽度再除2
left: (screenWidth-80*2-32)/2,
child: Row(
children: [
Container(
alignment: Alignment.center,
child: WheelChooser(
listWidth: 80,
listHeight: screenHeight*2/3 - 128,
itemSize: 56,
startPosition: hour,
selectTextStyle: const TextStyle(color: Colors.white),
unSelectTextStyle: const TextStyle(color: Colors.black),
onValueChanged: (value){
hour = value;
},
datas: List<int>.generate(24, (index) => index),
),
),
const SizedBox(width: 32,
child: Text(" : ",style: TextStyle(fontSize: 24,color: Colors.white),),
),
WheelChooser(
listWidth: 80,
listHeight: screenHeight*2/3 - 128,
itemSize: 56,
startPosition: minute,
selectTextStyle: const TextStyle(color: Colors.white),
unSelectTextStyle: const TextStyle(color: Colors.black),
onValueChanged: (value){minute = value;},
datas: List<int>.generate(60, (index) => index),
),
],
),
),
],
),
上面的示例代码完全按照实现方法中的内容来编写,并且在关键位置添加了注释。代码中需要注意的是深色背景的位置,它需要与滑动被选择的内容对齐,不然显示的效果
不太好。此外,时间中小时的选择范围是0-24,分钟的选择范围是0-60.大家可以依据项目的需求来调整。
最后,我们对本章回的做一个全面的总结: