【问题标题】:Passing Api Post Request for multiple Objects in Flutter在 Flutter 中传递多个对象的 Api Post 请求
【发布时间】:2022-10-06 08:54:28
【问题描述】:

这是我的 post api 代码,它适用于邮递员,但我如何从颤振端发布这个?我是新的。我尝试了不同的东西,但它不起作用

  • 请不要张贴文字图片。将原始文本复制到您的问题中。

标签: flutter object post


【解决方案1】:
    final response = await http.post(
      url,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(
        {
          'User': {'u_email': '...', ...}, 
          'Rider': {'v_mail': '...', ...}
        }
      )
    );

请参阅Send data to the internet 了解更多信息。

【讨论】:

    【解决方案2】:

    请使用 Dio 包。

    dio: ^4.0.6
    
     Map<String, dynamic> body = {
        'apiToken': apiToken,
        'langCode': 'en',
      };
    
    Response response = await dio.post('YOURAPI',
            options: d.Options(headers: body));
    

    在这里,我使用 Dio 包进行 api 调用。

    【讨论】:

      【解决方案3】:

      首先,您应该创建 PostModel、User 和 Rider 模型。每个类都应该有将数据转换为 json 格式的方法

      class PostModel
      {
         User user;
         Rider rider;
      
         Map<String,dynamic> toJson()=>_$ConvertPostModelToJson(this);
      }
      
      class Rider
      {
        String v_name;
        String v_number;
        String v_color;
        String v_email;
      
        Map<String,dynamic> toJson()=>_$ConvertRiderToJson(this);
      }
      
      class User
      {
         String u_email;
         String u_password;
         String u_role;
         String u_name;
         String u_contact;
       
         Map<String,dynamic> toJson()=>_$ConvertUserToJson(this);
      }
      

      您应该将 http 和 dart:convert 库导入到您的代码中以进行转换
      模型到 json 对象并将它们发送到服务器。

      You can find more information about http library

      You can find more information about json serialization

      You can find more information about sending model to server using post

      【讨论】:

      • 你能做一个功能来在 Flutter 中发布这个特定的数据帖子吗
      • 我已经创建了这些模型,但不知道为它创建一个函数
      猜你喜欢
      • 2019-03-12
      • 2016-01-25
      • 2019-08-03
      • 2017-11-11
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多