在上一篇文章中,我们掌握了如何通过时间对话框选择并显示时间内容,以及如何获取当前时间。
本文继续添加一个新的部件:多值单选。
启动 Android Studio,打开 hello_world
项目,运行虚拟机,这样就可以实时看到编码产生的效果。现在,我们的部件
页面展示了文本框,日期选择,时间选择,以及按钮四个部件。
- 在
lib/widget
文件夹下,打开my_widgets.dart
文件,定位到下列代码:
class _MyWidgetsState extends State<MyWidgets> {
- 在这一行代码的上方,添加下列代码:
enum Importance {
low,
medium,
high,
}
这里,我们定义了一个枚举,表示重要程度的三个等级:low(低),mdium(中),high(高)。
- 继续在
my_widgets.dart
文件中,定位到下列代码:
TimeOfDay _timeOfDay = TimeOfDay.now();
- 在这一行代码的下方,添加下列代码:
Importance _importance = Importance.low;
这里,我们定义了一个私有变量,保存用户选择的重要程度的值。
- 继续在
my_widgets.dart
文件中,定位到下列代码:
Widget buildTimeField(BuildContext context) {
- 在这一行代码的上方,添加下列代码:
Widget buildImportanceField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Row(
children: [
Text(
'重要性',
style: TextStyle(fontSize: 20.0),
)
],
),
Wrap(
spacing: 10.0,
children: [
ChoiceChip(
backgroundColor: Colors.grey,
selectedColor: Colors.lightBlue,
selected: _importance == Importance.low,
label: const Text(
'低',
style: TextStyle(color: Colors.white),
),
onSelected: (selected) {
setState(() => _importance = Importance.low);
},
),
ChoiceChip(
backgroundColor: Colors.grey,
selectedColor: Colors.lightBlue,
selected: _importance == Importance.medium,
label: const Text(
'中',
style: TextStyle(color: Colors.white),
),
onSelected: (selected) {
setState(() => _importance = Importance.medium);
},
),
ChoiceChip(
backgroundColor: Colors.grey,
selectedColor: Colors.lightBlue,
selected: _importance == Importance.high,
label: const Text(
'高',
style: TextStyle(color: Colors.white),
),
onSelected: (selected) {
setState(() => _importance = Importance.high);
},
),
],
),
],
);
}
这里,我们创建了一个多值选择部件,显示三个重要程度,用户只能选择其中一个选项。
- 继续在
my_widgets.dart
文件中,定位到下列代码:
buildMaterialButton(),
- 在这一行代码的上方,添加下列代码:
buildImportanceField(),
- 保存文件,热重启项目。点击
部件
导航图标,页面上出现了时间重要性
的选择部件,默认选择低
。
- 尝试选择其他两个值:中和高。
提交代码
我们已经实现了重要程度的显示和选择,又到达了一个小小的里程碑,应该对代码进行提交,保持良好编程习惯。
git add .
git commit -m '显示并选择重要程度。'