I'm sending a POST method using http in Flutter. but before i send/ POST i need to check if the data i'm sending already exist. so how can i achieve this kind of operation.
my Model for Users.
import 'dart:convert';
List<User> usersFromJson(String str) =>
List<User>.from(json.decode(str).map((json) => User.fromJson(json)));
String usersToJson(List<User> data) =>
json.encode(List<dynamic>.from(data.map((e) => e.toJson())));
class User {
int? id;
String? name;
String? username;
String? email;
String? role;
User({this.id, this.name, this.username, this.email, this.role});
@override
toString() => 'User: $name';
factory User.fromJson(Map<String, dynamic> json) => User(
email: json['email'],
name: json['name'],
id: json['id'],
username: json['username'],
role: json['role']);
Map<String, dynamic> toJson() =>
{"name": name, "username": username, "email": email, "role": role};
}
my Request
Future createUser(String name, String username, String email, String password,
String roles) async {
final UserController userController = Get.put(UserController());
Uri url = Uri.parse("${BASE_URL}user");
final response = await http
.post(url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $TOKEN',
},
body: jsonEncode(<String, dynamic>{
'name': name,
'email': email,
'username': username,
'password': password,
'roles': roles
}))
.then((value) => {
if (json.decode(value.body)['error'] == null)
{
userController.setuserPress(true),
Get.snackbar("created $name", "${value.body}",
duration: const Duration(seconds: 3),
colorText: Colors.black,
backgroundColor: Colors.white),
}
else
{
throw Get.snackbar("failed $name", "${value.body}",
duration: const Duration(seconds: 3),
colorText: Colors.black,
backgroundColor: Colors.white),
}
});
}
i'm using a form and validating it. so do i need to handle this in the form? or directly in the request?.. if so How can i achieve that?