You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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'),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

关键修改说明

  1. 移除了原代码中setState更新当前页面的逻辑,因为现在不需要在表单页面展示新增条目。
  2. 使用Navigator.push配合MaterialPageRoute实现页面跳转,通过构造函数将包含新条目的属性列表传递给AddedProperties页面。
  3. 保留了表单重置和成功提示的SnackBar,保证用户操作后的反馈体验。

如果不需要在原页面保留历史属性数据,也可以直接传递仅包含新条目的列表(比如[property]),根据你的业务需求调整即可。

内容的提问来源于stack exchange,提问作者Woke Vibes Hollys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:53:13