updateUser method
Updates a user.
token JWT authentication token.
userId User ID.
username New username (optional).
password New password (optional).
role New role - admin or user (optional).
Returns a Map with the updated data or null on error.
Example response:
{
"id": "1a457e1a-121a-11ee-be56-0242ac120002",
"username": "umami",
"role": "admin",
"createdAt": "2023-04-13T20:22:55.756Z"
}
Implementation
Future<Map<String, dynamic>?> updateUser({
required String token,
required String userId,
String? username,
String? password,
String? role,
}) async {
try {
final body = <String, dynamic>{};
if (username != null) body['username'] = username;
if (password != null) body['password'] = password;
if (role != null) body['role'] = role;
final response = await http.post(
Uri.parse('$endpoint/api/users/$userId'),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
},
body: jsonEncode(body),
);
if (response.statusCode == 200) {
return jsonDecode(response.body) as Map<String, dynamic>;
}
// Tenta decodificar o JSON de erro
try {
final errorJson = jsonDecode(response.body);
debugPrint('Failed to update user: ${response.statusCode}');
debugPrint('Error JSON: $errorJson');
} catch (e) {
debugPrint('Failed to update user: ${response.statusCode} ${response.body}');
}
return null;
} catch (e) {
debugPrint('Update user error: $e');
return null;
}
}