如何在flutter中使用http post而不需要500?

问题描述 投票:0回答:1

这是我的用户类别

class User {
  int? userId;
  String? username;
  String? password;
  String? email;
  String? phone;
  String? name;
  String? surname;

  User(
      {required this.userId,
      required this.username,
      required this.password,
      required this.email,
      required this.phone,
      required this.name,
      required this.surname});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      userId: json['userId'],
      username: json['userName'],
      password: json['password'],
      email: json['mail'],
      phone: json['phone'],
      name: json['name'],
      surname: json['surname'],
    );
  }
}

我使用这个uri,我可以在模拟器上成功使用Http get,但我不能使用post方法。

static final baseUrl = Uri.parse(
      "http://10.0.2.2:8080/users");

这是我的服务

Future<dynamic> createUser(User user) async {
    final url = Uri.parse('$baseUrl');

    Map<String, dynamic> request = {
      'userId': user.userId,
      'username': user.username,
      'password': user.password,
      'email': user.email,
      'phone': user.phone,
      'name': user.name,
      'surname': user.surname
    };

    final response = await http.post(
      url,
      headers: {
        'Content-Type': 'application/json',
      },
      body: jsonEncode(request),
    );

    if (response.statusCode == 201 || response.statusCode == 200) {
      return User.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to create user. ${response.statusCode}');
    }
  }

我(显然是我的代码:D)愿意接受任何建议

当我尝试使用假 API 时,它可以工作,但不在我的本地数据库中(我可以在 Postman 中完成)

flutter post http-post
1个回答
0
投票

检查这个包:它可能有帮助 https://pub.dev/packages/dio

© www.soinside.com 2019 - 2024. All rights reserved.