Error While Loading Products: ValidationError (Invalid key users_permissions_user)

Hi,
I’m encountering an error while trying to load products in my application. I encounter this error after logging in with a user, but I can’t determine whether the issue is related to the user or the items associated with them. Can someone clarify this for me?

The error details are as follows:

Exception: Ürünler yüklenemedi: {"data":null,"error":{"status":400,"name":"ValidationError","message":"Invalid key users_permissions_user","details":{"key":"users_permissions_user","path":null,"source":"query","param":"filters"}}}

Here’s what I’m working with:

  1. Backend: Strapi v5
  2. Frontend: Flutter
  3. Issue: The error seems related to a validation issue with the key users_permissions_user. I suspect it’s connected to filters or a query parameter sent from the frontend.

What I’ve tried so far:

  1. Checked the query parameters in the request to ensure there’s no unexpected key.
  2. Verified the content type settings in Strapi to ensure proper permissions are set.

Despite these efforts, the issue persists. Any help or suggestions would be greatly appreciated!

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/items.dart';

class CrudService {
  final String apiUrl = "http://10.0.2.2:1337/api/items";
  final String authUrl = "http://10.0.2.2:1337/api/auth/local";
  final String registerUrl = "http://10.0.2.2:1337/api/auth/local/register";

  final Logger _logger = Logger(); // Logger instance created.

  // User login
  Future<void> login(String identifier, String password) async {
    try {
      final response = await http.post(
        Uri.parse(authUrl),
        headers: {"Content-Type": "application/json"},
        body: jsonEncode({
          "identifier": identifier,
          "password": password,
        }),
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        String jwt = data['jwt'];
        String userId = data['user']['id'].toString();

        final prefs = await SharedPreferences.getInstance();
        await prefs.setString('token', jwt);
        await prefs.setString('userId', userId);

        _logger.i("Login successful, token: $jwt and user ID: $userId saved.");
      } else {
        _logger.w("Login failed: ${response.body}");
        throw Exception('Login failed: ${response.body}');
      }
    } catch (e) {
      _logger.e("Login Error: ${e.toString()}");
      rethrow;
    }
  }

  // Register new user
  Future<void> register(String username, String email, String password) async {
    try {
      final response = await http.post(
        Uri.parse(registerUrl),
        headers: {"Content-Type": "application/json"},
        body: jsonEncode({
          "username": username,
          "email": email,
          "password": password,
        }),
      );

      if (response.statusCode == 200 || response.statusCode == 201) {
        _logger.i("Registration successful: ${response.body}");
      } else {
        _logger.w("Registration failed: ${response.body}");
        throw Exception('Registration failed: ${response.body}');
      }
    } catch (e) {
      _logger.e("Register Error: ${e.toString()}");
      rethrow;
    }
  }

  // Get user ID
  Future<String?> getUserId() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString('userId');
  }

  // Get token
  Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString('token');
  }

  // List items (only the logged-in user's items)
  Future<List<Item>> fetchItems() async {
    try {
      final token = await getToken();
      final userId = await getUserId();

      if (token == null || userId == null) {
        _logger.w("Token or User ID not found.");
        throw Exception('Token or User ID not found. User is not logged in.');
      }

      final response = await http.get(
        Uri.parse("$apiUrl?filters[users_permissions_user][id][\$eq]=$userId&populate=Photo"),
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer $token",
        },
      );

      _logger.d("Fetch Response Status Code: ${response.statusCode}");
      _logger.d("Fetch Response Body: ${response.body}");

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);

        if (body['data'] == null) {
          throw Exception('No items found for the user');
        }

        return (body['data'] as List).map((item) => Item.fromJson(item)).toList();
      } else {
        _logger.e("Error: ${response.body}");
        throw Exception("Failed to load items: ${response.body}");
      }
    } catch (e) {
      _logger.e("FetchItems Error: ${e.toString()}");
      rethrow;
    }
  }

  // Add item
  Future<void> createItem(Item item, File? imageFile) async {
    try {
      final token = await getToken();
      final userId = await getUserId();

      if (token == null || userId == null) {
        _logger.w("Token or User ID not found.");
        throw Exception('Token or User ID not found.');
      }

      var request = http.MultipartRequest('POST', Uri.parse(apiUrl));
      request.headers['Authorization'] = 'Bearer $token';

      if (imageFile != null) {
        request.files.add(
          await http.MultipartFile.fromPath('files.Photo', imageFile.path),
        );
      }

      request.fields['data'] = jsonEncode({
        "Name": item.name,
        "Style": item.style,
        "Color": item.color,
        "users_permissions_user": {"id": userId},
      });

      final response = await request.send();
      final responseBody = await response.stream.bytesToString();
      _logger.d("Create Response Status Code: ${response.statusCode}");
      _logger.d("Create Response Body: $responseBody");

      if (response.statusCode != 200 && response.statusCode != 201) {
        _logger.w("Failed to add item: ${response.reasonPhrase}");
        throw Exception('Failed to add item: ${response.reasonPhrase}');
      }
    } catch (e) {
      _logger.e("CreateItem Error: ${e.toString()}");
      rethrow;
    }
  }
}