flutter代码 form表单内增加时间选择和获取音频时长class CalllogAddPage extends StatefulWidget const CalllogAddPageKey key superkey key; override StateCalllogAddPage createState = _CalllogAddPageState;class _CalllogA
为了在表单中添加时间选择和获取音频时长,我们可以使用两个组件: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字典中包含了所有必要的信息,我们将执行上传逻辑。
原文地址: https://www.cveoy.top/t/topic/bouz 著作权归作者所有。请勿转载和采集!