Flutter表单提交后跳转至AddedProperties页面的实现问题
解决方案
要实现点击Submit后跳转到AddedProperties页面并展示新增条目,你需要修改_submitForm函数,移除当前页面更新状态的逻辑,改用Flutter的导航API跳转到目标页面,并传递属性数据。
修改后的_submitForm函数
void _submitForm() { if (_formKey.currentState!.validate()) { final property = Property( name: _nameController.text, description: _descriptionController.text, pricePerMonth: double.parse(_priceController.text), ); // 将新条目添加到全局列表(如需保留历史数据) _allProperties.add(property); // 跳转到AddedProperties页面并传递属性列表 Navigator.push( context, MaterialPageRoute( builder: (context) => AddedProperties(properties: _allProperties), ), ); _resetForm(); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Property added successfully!'), duration: Duration(seconds: 2), ), ); } }
确保AddedProperties页面支持接收数据
你需要给AddedProperties页面添加构造函数来接收属性列表,并在页面中渲染这些条目:
class AddedProperties extends StatelessWidget { final List<Property> properties; // 构造函数接收属性列表 const AddedProperties({super.key, required this.properties}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Added Properties')), body: ListView.builder( itemCount: properties.length, itemBuilder: (context, index) { final currentProperty = properties[index]; return Card( margin: const EdgeInsets.all(8), child: Padding( padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( currentProperty.name, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 4), Text(currentProperty.description), const SizedBox(height: 4), Text('\$${currentProperty.pricePerMonth}/month'), ], ), ), ); }, ), ); } }
关键修改说明
- 移除了原代码中
setState更新当前页面的逻辑,因为现在不需要在表单页面展示新增条目。 - 使用
Navigator.push配合MaterialPageRoute实现页面跳转,通过构造函数将包含新条目的属性列表传递给AddedProperties页面。 - 保留了表单重置和成功提示的SnackBar,保证用户操作后的反馈体验。
如果不需要在原页面保留历史属性数据,也可以直接传递仅包含新条目的列表(比如[property]),根据你的业务需求调整即可。
内容的提问来源于stack exchange,提问作者Woke Vibes Hollys
相关产品推荐
相关产品推荐

