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

Flutter开发:如何将Form表单数据作为对象传递给API接口

Flutter Form表单封装数据对象传递给API的实现方案

你当前代码的核心问题是使用了普通TextField而非Form体系下的TextFormField,没有配置字段保存回调,直接调用save()无法拿到有效表单数据,按以下步骤修改即可:

步骤1:定义AddPost数据模型类

class AddPost {
  final String title;
  final String description;
  final double price;
  final String unit;

  AddPost({
    required this.title,
    required this.description,
    required this.price,
    required this.unit,
  });

  // 序列化方法,供API请求时转成后端可识别的JSON格式
  Map<String, dynamic> toJson() => {
    'title': title,
    'description': description,
    'price': price,
    'unit': unit,
  };
}

步骤2:修正Form表单内的输入组件

将所有TextField替换为TextFormField,给每个字段配置onSaved保存回调,同时可增加校验逻辑避免无效提交:

// 在当前页面的State类中先定义临时变量存储各字段输入值
String? _title;
String? _description;
double? _price;
String? _unit;

Form(
  key: _formKey,
  child: Column(
    children: [
      Seperator(),
      TextFormField(
        decoration: const InputDecoration(
          hintText: 'Add a title',
        ),
        onSaved: (value) => _title = value,
        validator: (value) => value?.isEmpty == true ? '请输入标题' : null,
      ),
      Seperator(),
      TextFormField(
        decoration: const InputDecoration(
          hintText: 'Add a description',
        ),
        onSaved: (value) => _description = value,
        validator: (value) => value?.isEmpty == true ? '请输入描述' : null,
      ),
      Seperator(),
      TextFormField(
        decoration: const InputDecoration(
          hintText: 'Add a Price',
        ),
        keyboardType: TextInputType.numberWithOptions(decimal: true),
        onSaved: (value) => _price = double.tryParse(value ?? ''),
        validator: (value) => double.tryParse(value ?? '') == null ? '请输入有效价格' : null,
      ),
      Seperator(),
      TextFormField(
        decoration: const InputDecoration(
          hintText: 'Select Unit',
        ),
        onSaved: (value) => _unit = value,
        validator: (value) => value?.isEmpty == true ? '请输入单位' : null,
      ),
      Button(
        isProcessing: isProcessing,
        name: 'Create Post',
        onPressed: () {
          // 先校验表单再执行保存逻辑
          if (_formKey.currentState!.validate()) {
            _formKey.currentState!.save();
            // 组装成AddPost对象
            final formData = AddPost(
              title: _title!,
              description: _description!,
              price: _price!,
              unit: _unit!,
            );
            createpost(formData);
          }
        },
      )
    ],
  ),
)

步骤3:调整API请求逻辑

在PostService的createpost方法中直接调用AddPost实例的toJson()方法序列化即可,示例:

class PostService {
  Future createpost(AddPost formData) async {
    // 替换为你实际使用的网络请求工具即可
    final dio = Dio();
    return await dio.post(
      '你的API接口地址',
      data: formData.toJson(),
    );
  }
}

// 原调用逻辑无需修改
createpost(AddPost formdata) async {
  try {
    final service = PostService();
    final response = await service.createpost(formdata);
    // 自行补充请求成功后的业务逻辑
  } catch (error) {
    setErrorMessage(error.toString());
  }
}

内容的提问来源于stack exchange,提问作者Febin Johnson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:15:01