import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:item_tracker/models/item_model.dart'; import 'package:item_tracker/provider/item_provider.dart'; DateTime? selectedDate; enum ItemIsUse { yes, no, } class AddItemScreen extends StatefulWidget { @override _FromTestRouteSate createState() => _FromTestRouteSate(); } class _FromTestRouteSate extends State { TextEditingController _nameController = TextEditingController(); TextEditingController _descriptionController = TextEditingController(); String? _selectedCategory; // 当前选中的分类 TextEditingController _locationController = TextEditingController(); ItemIsUse? _itemIsUse = ItemIsUse.yes; TextEditingController _priceController = TextEditingController(); GlobalKey _formKey = GlobalKey(); // 添加自定义分类列表 List _categories = ['A', 'B', 'C', 'D']; // 自定义分类 // 更新选中的分类 void _updateSelectedCategory(String? category) { setState(() { _selectedCategory = category; }); } @override Widget build(BuildContext context) { var date = selectedDate; void setGroupValue(ItemIsUse? itemIsUse) { setState(() { _itemIsUse = itemIsUse; }); } return Scaffold( appBar: AppBar( title: Text('新增物品'), ), body: Builder(builder: (context) { return Form( key: _formKey, autovalidateMode: AutovalidateMode.onUserInteraction, child: ListView( padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), children: [ TextFormField( autofocus: true, controller: _nameController, decoration: InputDecoration( labelText: "名称", hintText: "请输入物品名称", border: OutlineInputBorder(), ), maxLength: 20, validator: (v) { if (v == null || v.trim().isEmpty) { print('名称不能为空'); return "物品名称不能为空"; } return null; }, ), SizedBox(height: 16.0), TextField( controller: _descriptionController, decoration: InputDecoration( labelText: "物品描述", hintText: "请输入物品描述", border: OutlineInputBorder(), ), maxLines: 4, maxLength: 200, ), SizedBox(height: 16.0), DropdownButtonFormField( value: _selectedCategory, items: _categories.map((category) { return DropdownMenuItem( value: category, child: Text(category), ); }).toList(), onChanged: _updateSelectedCategory, decoration: InputDecoration( border: OutlineInputBorder(), filled: true, fillColor: Colors.grey[100], labelText: '请选择分类', ), ), SizedBox(height: 16.0), TextFormField( controller: _locationController, decoration: InputDecoration( labelText: "物品位置", hintText: "请输入物品位置", border: OutlineInputBorder(), ), ), SizedBox(height: 16.0), Text( date == null ? '请选择日期' : '已选择日期: ${date.year}年${date.month}月${date.day}日', ), SizedBox(height: 16.0), ElevatedButton.icon( icon: Icon(Icons.calendar_today, color: Colors.white), onPressed: () async { var pickedDate = await showDatePicker( context: context, initialEntryMode: DatePickerEntryMode.calendarOnly, initialDate: DateTime.now(), firstDate: DateTime(2015, 8), lastDate: DateTime(2101), ); setState(() { selectedDate = pickedDate; }); }, label: Text('选择日期', style: TextStyle(color: Colors.white)), style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), ), ), SizedBox(height: 16.0), Wrap( crossAxisAlignment: WrapCrossAlignment.center, spacing: 12, // 每个元素之间水平间距 runSpacing: 8, // 换行后垂直间距 children: [ Text( '请选择是否使用:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), Row( mainAxisSize: MainAxisSize.min, children: [ Radio( value: ItemIsUse.yes, groupValue: _itemIsUse, onChanged: setGroupValue, ), Text('是'), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ Radio( value: ItemIsUse.no, groupValue: _itemIsUse, onChanged: setGroupValue, ), Text('否'), ], ), ], ), SizedBox(height: 16.0), TextField( controller: _priceController, keyboardType: TextInputType.number, inputFormatters: [ FilteringTextInputFormatter.allow( RegExp(r'^\d*\.?\d{0,2}$'), ), ], decoration: InputDecoration( labelText: "物品价格", hintText: "请输入物品价格", border: OutlineInputBorder(), ), ), SizedBox(height: 28.0), ElevatedButton( child: Padding( padding: const EdgeInsets.all(16.0), child: Text("提交"), ), onPressed: () { if (_formKey.currentState!.validate()) { final newItem = Item( name: _nameController.text, description: _descriptionController.text, purchaseDate: selectedDate, ); print(newItem.toMap()); // 获取 ItemProvider 并添加物品 Provider.of(context, listen: false) .addItem(newItem); // 弹窗提示添加成功 ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('提交成功'), duration: Duration(seconds: 1), )); // 确保只有在表单验证成功后才调用 Navigator.pop Navigator.pop(context, true); } }, style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), elevation: 4.0, ), ), ], ), ); }), ); } }