Flutter-TextFormField上的Time.now()

时间:2019-05-16 11:55:25

标签: flutter timepicker

我在Flutter中添加了一个时间选择器。这样...

Future<Null> dataloggerHour(
      BuildContext context, TextEditingController controller) async {
    final TimeOfDay picked =
        await showTimePicker(context: context, initialTime: time);
    if (picked != null && picked != TimeOfDay.now()) {
      picked.format(context);
      setState(() {
        var transform = picked.format(context).split(" ");
        controller.text = transform[0];
      });
    }
  }

我需要将此日期添加到输入字段中。问题是,当我将此日期转换为字符串时,请删除左侧的零。

示例数据为:08:00,当解析返回80:0时。

我如何保持这个零?

3 个答案:

答案 0 :(得分:0)

official documentation中,它们重写toString方法以自动添加0。您需要使用.toString()方法。

@override
String toString() {
  String _addLeadingZeroIfNeeded(int value) {
    if (value < 10)
      return '0$value';
    return value.toString();
  }

  final String hourLabel = _addLeadingZeroIfNeeded(hour);
  final String minuteLabel = _addLeadingZeroIfNeeded(minute);

  return '$TimeOfDay($hourLabel:$minuteLabel)';
}

答案 1 :(得分:0)

如果要保留前导零,可以使用padLeft

String time = '8:00';
time = time.padLeft(5, '0'); // 08:00

上面的示例在字符串的长度小于5的情况下添加前导零。

答案 2 :(得分:0)

这应该有效

 DateTimePickerFormField(
                      lastDate: DateTime.now(),
                      inputType: inputType,
                      format: formats[inputType],
                      editable: editable,
                      decoration: InputDecoration(
                        errorText: _validate ? 'Cannot be left blank':null,
                          labelText: 'Date/Time',
                          hasFloatingPlaceholder: false,
                          filled: true,
                          fillColor: Colors.grey[300]),
                      onFieldSubmitted: (value) {
                        setState(() {
                          _//...........some code
                        });
                      },
                    ),