如何在选择的时间内添加秒数

how to add seconds in picked time

我正在使用 showTimePicker 小部件来选择时间,当我 select 时间时,它会像这样打印 7:10 PM 但我也想添加秒数,它应该是这样的7:10:00 PM秒可以默认00.

这是我创建这个的代码

 TextField(
        decoration: InputDecoration(labelText: timein,hintText: "Time in",icon: Icon(Icons.timer)),
        controller:timeinController ,
        readOnly:true,
        onTap: () async {
                  TimeOfDay pickedTime =  await showTimePicker(
                          initialTime: TimeOfDay.now(),
                          context: context,
                      );
        if(pickedTime != null ){
                      print(pickedTime.format(context));   //output 7:10 PM
                      setState(() {
                        timeinController.text = pickedTime.format(context);  //set the value of text field. 
                      });
                  }else{
                      print("Time is not selected");
                  }
                },
      ),

这里的 showtimepicker 看起来像

请帮助如何做到这一点。

TimeOfDay 不包括秒数,但 DateTime 提供了它,因此您可以从 DateTime 获取秒数并将其附加到 TimeOfDay,如下所示。

      TextField(
              decoration: InputDecoration(labelText: 'Time in',hintText: "Time in",icon: Icon(Icons.timer)),
              // controller: timeinController ,
              readOnly:true,
              onTap: () async {
                TimeOfDay? pickedTime =  await showTimePicker(
                  initialTime: TimeOfDay.now(),
                  context: context,
                );
                if(pickedTime != null ){
                  DateTime date = DateTime.now();
                  String second = date.second.toString().padLeft(2, '0');
                  List timeSplit = pickedTime.format(context).split(' ');
                  String formattedTime = timeSplit[0];
                  String time = '$formattedTime:$second';
                  String type = '';
                  if(timeSplit.length > 1) {
                    type = timeSplit[1];
                    time = '$time $type';
                  }

                  print(time); //output 7:10:00 PM
                  setState(() {
                    timeinController.text = pickedTime.format(context);  //set the value of text field.
                  });
                }else{
                  print("Time is not selected");
                }
              },
            )