feat:引入TDDesign组件
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:food_hub_app/widgets/common/index.dart';
|
||||
import 'package:form_builder_validators/form_builder_validators.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:tdesign_flutter/tdesign_flutter.dart';
|
||||
|
||||
class RecordFormPage extends StatefulWidget {
|
||||
const RecordFormPage({super.key});
|
||||
@@ -17,111 +17,231 @@ class RecordFormPage extends StatefulWidget {
|
||||
class _RecordFormPage extends State<RecordFormPage> {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
List<TextEditingController> _controller = [];
|
||||
FormController _formController = FormController();
|
||||
|
||||
String _selected_1 = '';
|
||||
String _selected_2 = '';
|
||||
String? _initLocalData;
|
||||
|
||||
final ImagePicker _picker = ImagePicker();
|
||||
XFile? _selectedImage;
|
||||
|
||||
// 选择图片的方法
|
||||
Future<void> _pickImage(ImageSource source) async {
|
||||
try {
|
||||
final XFile? image = await _picker.pickImage(source: source);
|
||||
if (image != null) {
|
||||
setState(() {
|
||||
_selectedImage = image;
|
||||
// 更新表单字段的值
|
||||
_formKey.currentState?.fields['image']?.didChange(image.path);
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('选择图片失败: $e')));
|
||||
}
|
||||
}
|
||||
/// 整个表单存放的数据
|
||||
Map<String, dynamic> _formData = {
|
||||
"name": '',
|
||||
"date": '',
|
||||
"gender": '',
|
||||
"birth": '',
|
||||
"place": '',
|
||||
"age": "2",
|
||||
"description": "2",
|
||||
"resume": '',
|
||||
"photo": '',
|
||||
};
|
||||
|
||||
Map<String, dynamic> _formItemNotifier = {
|
||||
"name": '',
|
||||
"password": '',
|
||||
"gender": '',
|
||||
"birth": '',
|
||||
"place": '',
|
||||
"age": '2',
|
||||
"description": '',
|
||||
"resume": '',
|
||||
"photo": "",
|
||||
};
|
||||
|
||||
/// 定义整个校验规则
|
||||
final Map<String, TDFormValidation> _validationRules = {
|
||||
'name': TDFormValidation(
|
||||
validate: (value) => value == null || value.isEmpty ? 'empty' : null,
|
||||
errorMessage: '输入不能为空',
|
||||
type: TDFormItemType.input,
|
||||
),
|
||||
"birth": TDFormValidation(
|
||||
validate: (value) => value == null || value.isEmpty ? 'empty' : null,
|
||||
errorMessage: '不能为空',
|
||||
type: TDFormItemType.dateTimePicker,
|
||||
),
|
||||
"photo": TDFormValidation(
|
||||
validate: (value) => value == null || value.isEmpty ? 'empty' : null,
|
||||
errorMessage: '不能为空',
|
||||
type: TDFormItemType.upLoadImg,
|
||||
),
|
||||
};
|
||||
|
||||
void confirmClick(BuildContext context) {
|
||||
if (_formKey.currentState?.saveAndValidate() ?? false) {
|
||||
showSuccessToast("新增记录成功");
|
||||
// showSuccessToast("新增记录成功");
|
||||
} else {
|
||||
showErrorToast("请先提交信息");
|
||||
// showErrorToast("请先提交信息");
|
||||
}
|
||||
}
|
||||
|
||||
// 显示图片操作弹窗(查看/删除)
|
||||
Future<void> _showImageActionDialog(BuildContext context) async {
|
||||
await showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('图片操作'),
|
||||
actions: [
|
||||
// 查看图片
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
_previewImage(context);
|
||||
},
|
||||
child: const Text('查看'),
|
||||
),
|
||||
// 删除图片
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_selectedImage = null; // 清空选中的图片
|
||||
});
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: const Text(
|
||||
'删除',
|
||||
style: TextStyle(color: Colors.red),
|
||||
),
|
||||
),
|
||||
],
|
||||
List<TDUploadFile> files = [];
|
||||
|
||||
List<TDUploadFile> _onValueChanged(
|
||||
List<TDUploadFile> fileList,
|
||||
List<TDUploadFile> value,
|
||||
TDUploadType event,
|
||||
) {
|
||||
switch (event) {
|
||||
case TDUploadType.add:
|
||||
fileList.addAll(value);
|
||||
break;
|
||||
case TDUploadType.remove:
|
||||
fileList.removeWhere((element) => element.key == value[0].key);
|
||||
break;
|
||||
case TDUploadType.replace:
|
||||
final firstReplaceFile = value.first;
|
||||
final index = fileList.indexWhere(
|
||||
(file) => file.key == firstReplaceFile.key,
|
||||
);
|
||||
if (index != -1) {
|
||||
fileList[index] = firstReplaceFile;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return fileList;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
/// 三个文本型的表格单元
|
||||
for (var i = 0; i < 4; i++) {
|
||||
_controller.add(TextEditingController());
|
||||
}
|
||||
_formData.forEach((key, value) {
|
||||
_formItemNotifier[key] = FormItemNotifier();
|
||||
});
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// TODO: implement dispose
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String parseDatePickerSelected(Map<String, int> selected) {
|
||||
final String year = selected['year'].toString().padLeft(4, '0');
|
||||
final String month = selected['month'].toString().padLeft(2, '0');
|
||||
final String day = selected['day'].toString().padLeft(2, '0');
|
||||
|
||||
return '$year-$month-$day';
|
||||
}
|
||||
|
||||
TDFormItem buildNameItem() {
|
||||
return TDFormItem(
|
||||
label: '菜谱名称',
|
||||
name: 'name',
|
||||
type: TDFormItemType.input,
|
||||
labelWidth: 82.0,
|
||||
showErrorMessage: true,
|
||||
requiredMark: true,
|
||||
child: TDInput(
|
||||
leftContentSpace: 0,
|
||||
inputDecoration: InputDecoration(
|
||||
hintText: "请输入菜谱名称",
|
||||
border: InputBorder.none,
|
||||
hintStyle: TextStyle(color: TDTheme.of(context).grayColor6),
|
||||
),
|
||||
backgroundColor: Colors.white,
|
||||
additionInfoColor: TDTheme.of(context).errorColor6,
|
||||
showBottomDivider: false,
|
||||
onChanged: (val) {
|
||||
_formData['name'] = val;
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 显示选择图片来源的弹窗(相册/相机)
|
||||
Future<void> _showImageSourceDialog(BuildContext context) async {
|
||||
await showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('选择图片来源'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
_pickImage(ImageSource.gallery);
|
||||
},
|
||||
child: const Text('相册'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
_pickImage(ImageSource.camera);
|
||||
},
|
||||
child: const Text('相机'),
|
||||
),
|
||||
],
|
||||
TDFormItem buildDateItem() {
|
||||
return TDFormItem(
|
||||
label: '完成时间',
|
||||
name: 'date',
|
||||
labelWidth: 82.0,
|
||||
type: TDFormItemType.dateTimePicker,
|
||||
contentAlign: TextAlign.left,
|
||||
tipAlign: TextAlign.left,
|
||||
hintText: '请选择完成时间',
|
||||
select: _formData['date'],
|
||||
selectFn: (BuildContext context) {
|
||||
TDPicker.showDatePicker(
|
||||
context,
|
||||
title: '选择时间',
|
||||
onConfirm: (selected) {
|
||||
setState(() {
|
||||
print(selected);
|
||||
_selected_1 =
|
||||
'${selected['year'].toString().padLeft(4, '0')}-${selected['month'].toString().padLeft(2, '0')}-${selected['day'].toString().padLeft(2, '0')}';
|
||||
_formItemNotifier['birth']?.upDataForm(_selected_1);
|
||||
});
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
dateStart: [1999, 01, 01],
|
||||
dateEnd: [2050, 12, 31],
|
||||
initialDate: [2012, 1, 1],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
TDFormItem buildImageItem() {
|
||||
return TDFormItem(
|
||||
label: '上传图片',
|
||||
name: 'photo',
|
||||
labelWidth: 82.0,
|
||||
type: TDFormItemType.upLoadImg,
|
||||
formItemNotifier: _formItemNotifier['photo'],
|
||||
child: TDUpload(
|
||||
files: files,
|
||||
onError: print,
|
||||
onValidate: print,
|
||||
onChange: ((imgList, type) {
|
||||
files = _onValueChanged(files ?? [], imgList, type);
|
||||
List imgs = files.map((e) => e.remotePath ?? e.assetPath).toList();
|
||||
setState(() {
|
||||
_formItemNotifier['photo'].upDataForm(imgs.join(','));
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 预览图片(全屏查看)
|
||||
void _previewImage(BuildContext context) {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
body: Center(
|
||||
child: Image.file(
|
||||
File(_selectedImage!.path),
|
||||
fit: BoxFit.contain,
|
||||
Widget buildFormBtnGroup() {
|
||||
return Container(
|
||||
decoration: BoxDecoration(color: TDTheme.of(context).whiteColor1),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TDButton(
|
||||
text: '重置',
|
||||
type: TDButtonType.fill,
|
||||
theme: TDButtonTheme.light,
|
||||
shape: TDButtonShape.rectangle,
|
||||
onTap: () {
|
||||
//用户名称
|
||||
_controller[0].clear();
|
||||
//密码
|
||||
_controller[1].clear();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
floatingActionButton: IconButton(
|
||||
icon: const Icon(Icons.close, color: Colors.white),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
SizedBox(width: 20),
|
||||
Expanded(
|
||||
child: TDButton(
|
||||
text: '提交',
|
||||
type: TDButtonType.fill,
|
||||
theme: TDButtonTheme.primary,
|
||||
shape: TDButtonShape.rectangle,
|
||||
onTap: () => {},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -133,132 +253,20 @@ class _RecordFormPage extends State<RecordFormPage> {
|
||||
appBar: AppBar(title: Text('新增记录'), backgroundColor: Colors.white),
|
||||
backgroundColor: Color(0xFFF5F5F5),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
FormBuilder(
|
||||
key: _formKey,
|
||||
initialValue: {'date': DateTime.now(), 'accept_terms': false},
|
||||
skipDisabled: true,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
formLabelText(labelText: '菜谱名称', isRequired: true),
|
||||
const SizedBox(height: 5),
|
||||
FormBuilderTextField(
|
||||
name: 'name',
|
||||
decoration: formInputDecoration(hintText: '请输入或选择菜谱名称'),
|
||||
// onChanged: (val) => print(val),
|
||||
validator: FormBuilderValidators.compose([
|
||||
FormBuilderValidators.required(),
|
||||
FormBuilderValidators.minLength(3),
|
||||
FormBuilderValidators.maxLength(70),
|
||||
]),
|
||||
keyboardType: TextInputType.name,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
formLabelText(labelText: '完成时间', isRequired: true),
|
||||
const SizedBox(height: 5),
|
||||
FormBuilderDateTimePicker(
|
||||
name: 'date',
|
||||
decoration: formInputDecoration(
|
||||
hintText: '请选择日期',
|
||||
prefixIcon: Icons.date_range,
|
||||
),
|
||||
inputType: InputType.date,
|
||||
firstDate: DateTime(1900),
|
||||
lastDate: DateTime(2100),
|
||||
format: DateFormat('yyyy-MM-dd'),
|
||||
// enabled: _formKey.currentState?.fields['date']?.enabled ?? true,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
formLabelText(labelText: '美食图片'),
|
||||
const SizedBox(height: 5),
|
||||
|
||||
// 图片选择区域(核心优化部分)
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
// 已选择图片时,显示操作弹窗;未选择时直接打开选择器
|
||||
if (_selectedImage != null) {
|
||||
_showImageActionDialog(context);
|
||||
} else {
|
||||
_showImageSourceDialog(context); // 弹出选择相册/相机的对话框
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
height: 200,
|
||||
width: 200,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: Colors.grey[300]!,
|
||||
width: 1,
|
||||
style: BorderStyle.solid,
|
||||
),
|
||||
// 有图片时显示图片,无图片时显示背景色
|
||||
color:
|
||||
_selectedImage == null ? Colors.grey[50] : null,
|
||||
image:
|
||||
_selectedImage != null
|
||||
? DecorationImage(
|
||||
image: FileImage(
|
||||
File(_selectedImage!.path),
|
||||
),
|
||||
fit: BoxFit.contain,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
// 初始状态显示+号;有图片时隐藏
|
||||
child:
|
||||
_selectedImage == null
|
||||
? Center(
|
||||
child: Icon(
|
||||
Icons.add,
|
||||
color: Colors.grey[400],
|
||||
size: 48, // 大号+号,视觉更清晰
|
||||
),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
|
||||
// 隐藏的表单字段(保留原功能)
|
||||
FormBuilderTextField(
|
||||
name: 'image',
|
||||
initialValue: _selectedImage?.path ?? '',
|
||||
enabled: false,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '请选择一张图片';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: ElevatedButton(
|
||||
style: primaryButtonStyle(),
|
||||
onPressed: () => confirmClick(context),
|
||||
child: buttonText(text: '确认'),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 20),
|
||||
Expanded(
|
||||
child: ElevatedButton(
|
||||
style: cancelButtonStyle(),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: buttonText(text: '取消'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
child: SingleChildScrollView(
|
||||
child: TDForm(
|
||||
formController: _formController,
|
||||
data: _formData,
|
||||
rules: _validationRules,
|
||||
formContentAlign: TextAlign.left,
|
||||
formShowErrorMessage: true,
|
||||
onSubmit: () => {},
|
||||
items: [buildNameItem(), buildDateItem(), buildImageItem()],
|
||||
btnGroup: [buildFormBtnGroup()],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user