Flutter 3 基础13: 多值单选

78 阅读2分钟

上一篇文章中,我们掌握了如何通过时间对话框选择并显示时间内容,以及如何获取当前时间。

本文继续添加一个新的部件:多值单选。

启动 Android Studio,打开 hello_world 项目,运行虚拟机,这样就可以实时看到编码产生的效果。现在,我们的部件页面展示了文本框,日期选择,时间选择,以及按钮四个部件。

Screenshot_20231022_083738.png

  1. lib/widget 文件夹下,打开 my_widgets.dart 文件,定位到下列代码:
class _MyWidgetsState extends State<MyWidgets> {
  1. 在这一行代码的上方,添加下列代码:
enum Importance {
  low,
  medium,
  high,
}

这里,我们定义了一个枚举,表示重要程度的三个等级:low(低),mdium(中),high(高)。

  1. 继续在 my_widgets.dart 文件中,定位到下列代码:
TimeOfDay _timeOfDay = TimeOfDay.now();
  1. 在这一行代码的下方,添加下列代码:
Importance _importance = Importance.low;

这里,我们定义了一个私有变量,保存用户选择的重要程度的值。

  1. 继续在 my_widgets.dart 文件中,定位到下列代码:
Widget buildTimeField(BuildContext context) {
  1. 在这一行代码的上方,添加下列代码:
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);  
            },  
          ),  
        ],  
      ),  
    ],  
  );  
}

这里,我们创建了一个多值选择部件,显示三个重要程度,用户只能选择其中一个选项。

  1. 继续在 my_widgets.dart 文件中,定位到下列代码:
buildMaterialButton(),
  1. 在这一行代码的上方,添加下列代码:
buildImportanceField(),
  1. 保存文件,热重启项目。点击部件导航图标,页面上出现了时间重要性的选择部件,默认选择

Screenshot_20231023_085728.png

  1. 尝试选择其他两个值:中和高。

Screenshot_20231023_093025.png

Screenshot_20231023_093033.png

提交代码

我们已经实现了重要程度的显示和选择,又到达了一个小小的里程碑,应该对代码进行提交,保持良好编程习惯。

git add .
git commit -m '显示并选择重要程度。'