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

Flutter中如何从Future返回完整的OrderEventResponse响应

解决方案

1. 定义OrderEventResponse实体类

先把API返回的结构转换成Dart实体类,包含你需要的所有字段(比如success、articleResponseMessage),同时实现JSON序列化逻辑:

class OrderEventResponse {
  final bool success;
  final String? articleResponseMessage;
  // 可根据API返回添加其他字段,比如errorCode、data等

  OrderEventResponse({
    required this.success,
    this.articleResponseMessage,
  });

  // 从JSON解析为实体对象
  factory OrderEventResponse.fromJson(Map<String, dynamic> json) {
    return OrderEventResponse(
      success: json['success'] ?? false,
      articleResponseMessage: json['articleResponseMessage'],
    );
  }
}

2. 修改OrderEvent类的get方法

将原方法的返回类型从Future<bool>改为Future<OrderEventResponse>,请求成功时解析JSON生成实体对象,失败时捕获并抛出异常(也可在实体类中新增error字段统一处理错误):

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

class OrderEvent {
  Future<OrderEventResponse> get(Map<String, dynamic> body) async {
    try {
      // 发起POST请求
      final response = await http.post(
        Uri.parse('你的API接口地址'),
        body: body,
      );

      if (response.statusCode == 200) {
        // 解析返回的JSON为实体类
        return OrderEventResponse.fromJson(json.decode(response.body));
      } else {
        // 处理非200状态码的错误
        final errorData = json.decode(response.body);
        throw Exception(errorData['message'] ?? '请求失败');
      }
    } catch (e) {
      // 捕获网络异常等情况
      throw Exception('网络错误: $e');
    }
  }
}

3. 在Widget中调用方法

注意get方法是异步的,必须用async/await处理:

// 示例:在按钮点击事件中调用
onPressed: () async {
  try {
    // 构建请求体(从TextField获取输入)
    final requestBody = {
      'username': _usernameController.text,
      'orderId': _orderIdController.text,
      // 其他需要的字段
    };

    OrderEventResponse result = await OrderEvent().get(requestBody);
    bool resultSuccess = result.success;
    String resultMessages = result.articleResponseMessage ?? '无返回消息';
    
    // 后续业务处理,比如更新UI、弹窗提示等
    print('请求状态:$resultSuccess');
    print('返回消息:$resultMessages');
  } catch (e) {
    // 处理请求异常
    print('请求出错:$e');
  }
},

注意事项

  • 若API返回更多字段,需在OrderEventResponse中添加对应属性,并完善fromJson方法的解析逻辑
  • 异常处理可根据业务需求调整,比如自定义异常类区分网络错误、业务错误等
  • 确保已在pubspec.yaml中添加http包依赖(如http: ^1.1.0,可使用最新版本)

内容的提问来源于stack exchange,提问作者Dean Ball

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:50:20