为了在表单中添加时间选择和获取音频时长,我们可以使用两个组件:DateTimePicker 和 flutter_audio_recorder。

首先,我们需要添加这两个依赖库:

dependencies:
  flutter_datetime_picker: ^2.0.0
  flutter_audio_recorder: ^3.0.0

然后,我们可以在表单中添加一个 DateTimePicker 来选择时间:

TextButton(
  onPressed: () {
    DatePicker.showDateTimePicker(
      context,
      showTitleActions: true,
      onChanged: (date) {
        print('change $date');
      },
      onConfirm: (date) {
        setState(() {
          _param['time'] = date;
        });
      },
      currentTime: DateTime.now(),
      locale: LocaleType.zh,
    );
  },
  child: Text(
    _param['time'] == null
        ? '选择时间'
        : DateFormat('yyyy-MM-dd HH:mm:ss').format(_param['time']),
  ),
),

在这个例子中,我们使用了 flutter_datetime_picker 库中的 DatePicker 组件来显示一个时间选择器。当用户选择时间时,我们将选择的时间保存在 _param 字典中。

接下来,我们可以使用 flutter_audio_recorder 库来获取音频时长。我们可以在文件选择后使用 flutter_audio_recorder 库来获取音频的时长,然后将其保存在 _param 字典中。

FilePickerResult? result = await FilePicker.platform.pickFiles(
  dialogTitle: '录音选择',
  type: FileType.audio,
);
if (result != null) {
  String? file = result.files.single.path;
  path = file;
  setState(() {});
  AudioPlayer audioPlayer = AudioPlayer();
  AudioMetadata metadata = await audioPlayer.getMetadata(file: file);
  setState(() {
    _param['duration'] = metadata.duration;
  });
} else {
  // User canceled the picker
}

在这个例子中,我们使用了 flutter_audio_recorder 库中的 AudioPlayer 组件来获取音频的元数据,包括时长。当获取到元数据后,我们将时长保存在 _param 字典中。

最后,我们可以在上传按钮的点击事件中检查 _param 字典是否包含了所有必要的信息:

ElevatedButton(
  onPressed: () {
    FormState _form = _formKey.currentState as FormState;
    _form.save();
    if (_form.validate()) {
      if (_param.length < 3) {
        EasyLoading.showError('请填写完内容');
        return;
      }
      // 上传逻辑
    }
  },
  child: Text('上传'),
),

在这个例子中,我们检查 _param 字典中是否包含了时间、文件路径和时长这三个键。如果缺少其中任何一个,我们将显示一个错误提示。如果 _param 字典中包含了所有必要的信息,我们将执行上传逻辑。

Flutter 表单:添加时间选择器和获取音频时长

原文地址: https://www.cveoy.top/t/topic/mRhk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录