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

Flutter中如何借助Modal类通过API调用Post方法提交数据

Flutter 结合Modal类POST提交API数据实现步骤

1. 前置准备:添加网络请求依赖

在pubspec.yaml的dependencies节点下添加官方http包,执行flutter pub get完成安装:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.2.1 # 可替换为最新稳定版

安卓端需要在android/app/src/main/AndroidManifest.xml的manifest节点下添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

iOS端如果请求的是HTTP接口,需要在ios/Runner/Info.plist的dict节点下添加配置:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

2. 创建对应业务的Modal数据模型

根据接口要求的传参结构创建模型类,核心需要实现toJson方法,将类属性转换为接口可接收的序列化格式:

class SubmitModal {
  // 此处属性替换为你的接口要求传参字段
  final String name;
  final String phone;
  final int age;

  SubmitModal({
    required this.name,
    required this.phone,
    required this.age,
  });

  // 转换为JSON Map
  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'phone': phone,
      'age': age,
    };
  }
}

你问题中附的流程对应Modal封装、序列化、请求、响应解析的全流程:
提交流程

3. 封装POST请求方法

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Map<String, dynamic>> postSubmitData(SubmitModal data) async {
  // 替换为你的实际接口地址
  final apiUrl = Uri.parse('https://你的接口地址/submit');
  try {
    final response = await http.post(
      apiUrl,
      headers: {
        'Content-Type': 'application/json',
        // 接口需要鉴权的话可在此添加token等参数
        // 'Authorization': 'Bearer 你的token'
      },
      // 将Modal实例序列化为JSON字符串
      body: jsonEncode(data.toJson()),
    );

    if (response.statusCode == 200) {
      // 请求成功,解析返回结果
      return jsonDecode(response.body);
    } else {
      return {'code': response.statusCode, 'msg': '请求失败'};
    }
  } catch (e) {
    return {'code': -1, 'msg': '网络异常:$e'};
  }
}

如果接口要求接收form-data格式参数,无需设置Content-Type为application/json,body直接传入data.toJson()即可。

4. 业务层调用示例

以点击提交按钮触发请求为例:

ElevatedButton(
  onPressed: () async {
    // 1. 实例化Modal,传入用户输入的业务数据
    final submitData = SubmitModal(
      name: nameInputController.text,
      phone: phoneInputController.text,
      age: int.parse(ageInputController.text),
    );
    // 2. 调用提交方法
    final result = await postSubmitData(submitData);
    // 3. 处理返回结果
    if (result['code'] == 200) {
      // 提交成功逻辑,比如跳转页面、弹出成功提示
    } else {
      // 提交失败逻辑,弹出错误提示
    }
  },
  child: const Text('提交数据'),
)

内容的提问来源于stack exchange,提问作者Mahaveer Singh Kasana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:45:04