Skip to content

Unable to retrieve data from my supabase database #1128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Cleevemadjouh opened this issue Mar 7, 2025 · 3 comments
Open

Unable to retrieve data from my supabase database #1128

Cleevemadjouh opened this issue Mar 7, 2025 · 3 comments
Labels
bug Something isn't working postgrest This issue or pull request is related to postgrest

Comments

@Cleevemadjouh
Copy link

Cleevemadjouh commented Mar 7, 2025

Hello, on my application the goal is to create a product, add the name, description, price, city and say if it is a new product or not. Then publish the product. The product arrives in my database but I can not retrieve the product and its information to put them on my home page.

Here is a set of screenshots of my database and error:

A Dart VM Service on iPhone 14 Pro is available at:
http://127.0.0.1:65219/9mPpn-pzT6s=/
The Flutter DevTools debugger and profiler on iPhone 14 Pro is available at:
http://127.0.0.1:9101?uri=http://127.0.0.1:65219/9mPpn-pzT6s=/
flutter: \^[[38;5;12m┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────<…>
flutter: \^[[38;5;12m│ #0   _AddProductPageState._publishProduct (package:ecommerceapp/screens/add_product_page.dart:316:12)<…>
flutter: \^[[38;5;12m│ #1   <asynchronous suspension><…>
flutter: \^[[38;5;12m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄<…>
flutter: \^[[38;5;12m│ 💡 Image paths: [https://dkysfmevzveidazbbkqh.supabase.co/storage/v1/object/public/images-produits/products/1741339634024_0.jpg]<…>
flutter: \^[[38;5;12m└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────<…>
flutter: \^[[38;5;12m┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────<…>
flutter: \^[[38;5;12m│ #0   _AddProductPageState._publishProduct (package:ecommerceapp/screens/add_product_page.dart:354:20)<…>
flutter: \^[[38;5;12m│ #1   <asynchronous suspension><…>
flutter: \^[[38;5;12m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄<…>
flutter: \^[[38;5;12m│ 💡 Fichier supprimé : /Users/cleevemadjouh/Library/Developer/CoreSimulator/Devices/FC198355-DA86-4C14-8EB5-CC0C8C0FFCD8/data/Containers/Data/Application/213D5042-2E9E-44EE-A8A5-AD6FC8AF5E83/tmp/image_picker_3DD7E2CF-D538-483E-AB31-96B8AB01DB2B-23255-0000047178DFABA7.jpg_compressed.jpg<…>
flutter: \^[[38;5;12m└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────<…>
flutter: \^[[38;5;196m┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────<…>
flutter: \^[[38;5;196m│ FormatException: Unexpected end of input (at character 1)<…>
flutter: \^[[38;5;196m│ <…>
flutter: \^[[38;5;196m│ ^<…>
flutter: \^[[38;5;196m│ <…>
flutter: \^[[38;5;196m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄<…>
flutter: \^[[38;5;196m│ #0   HomePageState._fetchProducts (package:ecommerceapp/screens/home_page.dart:52:14)<…>
flutter: \^[[38;5;196m│ #1   <asynchronous suspension><…>
flutter: \^[[38;5;196m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄<…>
flutter: \^[[38;5;196m│ ⛔ Erreur lors du chargement des produits : <…>
flutter: \^[[38;5;196m└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────<…>

Application finished.
Image Image Image Image

My product.dar code :

import 'package:flutter/foundation.dart';

class Product {
  final int id;
  final String name;
  final double price;
  final String description;
  final String imageUrl;
  final String sellerId;
  final String city;
  final String? category;
  final String? condition;
  final List<String> imageUrls;
  final DateTime created_at;

  Product({
    required this.id,
    required this.name,
    required this.price,
    required this.description,
    required this.imageUrl,
    required this.sellerId,
    required this.city,
    this.category,
    this.condition,
    this.imageUrls = const [],
    required this.created_at,
  });

  factory Product.fromJson(Map<String, dynamic> json) {
    try {
      final id = json['id'] is int
          ? json['id']
          : int.parse(json['id'].toString());

      final dynamic priceValue = json['price'];
      double price;
      if (priceValue is int) {
        price = priceValue.toDouble();
      } else if (priceValue is double) {
        price = priceValue;
      } else if (priceValue is String) {
        price = double.parse(priceValue);
      } else {
        throw FormatException('Format de prix invalide');
      }

      List<String> imageUrls = [];
      if (json['imageUrls'] != null) {
        imageUrls = (json['imageUrls'] as List<dynamic>)
            .map((url) => url.toString())
            .toList();
      }

      DateTime created_at = json['created_at'] != null
    ? DateTime.parse(json['created_at'] as String) // Correction déjà faite
    : DateTime.now();

      return Product(
        id: id,
        name: json['name'] ?? '',
        price: price,
        description: json['description'] ?? '',
        imageUrl: json['imageUrl'] ?? '',
        sellerId: json['seller_id'] ?? '',
        city: json['city'] ?? '',
        category: json['category'],
        condition: json['condition'],
        imageUrls: imageUrls,
        created_at: created_at,
      );
    } catch (e) {
      if (kDebugMode) {
        print('Erreur lors de la création du produit depuis JSON: $e');
      }
      rethrow;
    }
  }

  Map<String, dynamic> toJson() {
    try {
      return {
        'id': id,
        'name': name,
        'price': price,
        'description': description,
        'imageUrl': imageUrl,
        'seller_id': sellerId,
        'city': city,
        'category': category,
        'condition': condition,
        'imageUrls': imageUrls,
        'created_at': created_at.toIso8601String(),
      };
    } catch (e) {
      if (kDebugMode) {
        print('Erreur lors de la conversion du produit en Map: $e');
      }
      rethrow;
    }
  }

  bool isValid() {
    try {
      return id > 0 &&
          name.isNotEmpty &&
          price >= 0 &&
          description.isNotEmpty &&
          city.isNotEmpty;
    } catch (e) {
      if (kDebugMode) {
        print('Erreur lors de la validation du produit: $e');
      }
      return false;
    }
  }

  @override
  String toString() {
    return 'Product{id: $id, name: $name, price: $price, description: $description, '
        'city: $city, category: $category, condition: $condition}';
  }

  Product copyWith({
    int? id,
    String? name,
    double? price,
    String? description,
    String? imageUrl,
    String? sellerId,
    String? city,
    String? category,
    String? condition,
    List<String>? imageUrls,
    DateTime? created_at,
  }) {
    return Product(
      id: id ?? this.id,
      name: name ?? this.name,
      price: price ?? this.price,
      description: description ?? this.description,
      imageUrl: imageUrl ?? this.imageUrl,
      sellerId: sellerId ?? this.sellerId,
      city: city ?? this.city,
      category: category ?? this.category,
      condition: condition ?? this.condition,
      imageUrls: imageUrls ?? this.imageUrls,
      created_at: created_at ?? this.created_at,
    );
  }
}

My fetch methode:

Future<void> _fetchProducts() async {
    
    try {
      productsFuture =
          ProductService().fetchProducts(); // Utilise ProductService
      final products = await productsFuture;
      setState(() {
        allProducts = products;
        displayedProducts = products;
      });

    } catch (e) {
      logger.e("Erreur lors du chargement des produits : ", error: e);
      // Affiche un message d'erreur à l'utilisateur
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Erreur lors du chargement des produits : $e"),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
@Vinzent03
Copy link
Collaborator

When opening issues please follow the appropriate issue templates like the bug template in this case.
None of your code snippets contain any usage of a supabase library, so there is no way for us to backtrack any issue to this library. Please share the implementation of ProductService().fetchProducts() and the exact stack trace of the exception, which you are not getting in your _fetchProducts() try-catch.

@Vinzent03 Vinzent03 added the bug Something isn't working label Mar 8, 2025
@Cleevemadjouh
Copy link
Author

Cleevemadjouh commented Mar 9, 2025

  1. Error Description
    The error I’m encountering is:

FormatException: Unexpected end of input (at character 1)

  1. Stack Trace
    Here’s the stack trace:
#0   HomePageState._fetchProducts (package:ecommerceapp/screens/home_page.dart:52:14)
#1   <asynchronous suspension>
  1. Code Snippets
    Here are the relevant code snippets:

a. _fetchProducts Method (home_page.dart)

Future<void> _fetchProducts() async {
  try {
    productsFuture = ProductService().fetchProducts(); // Fetch products using ProductService
    final products = await productsFuture;
    setState(() {
      allProducts = products;
      displayedProducts = products;
    });
  } catch (e) {
    logger.e("Error loading products: ", error: e);
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text("Error loading products: $e"),
        backgroundColor: Colors.red,
      ),
    );
  }
}

b. fetchProducts Method (product_service.dart)

Future<List<Product>> fetchProducts() async {
  try {
    _logger.d('Fetching products...');

    final response = await _supabase.from('products').select();

    // Check if the response is empty or null
    if (response == null || response.isEmpty) {
      _logger.w('No products found or empty response');
      return [];
    }

    // Convert the response to a list of Product objects
    final products = (response as List)
        .map((productJson) =>
            Product.fromJson(productJson as Map<String, dynamic>))
        .toList();

    _logger.i('${products.length} products fetched');
    return products;
  } catch (e) {
    _logger.e('Error fetching products: $e');
    return [];
  }
}

@Vinzent03
Copy link
Collaborator

Please check your text content after creating issue or comment, because your code is not readable if you use single backticks because the text is put into one line. Use triple backticks for code blocks. (I already edited your comments)

Your stacktrace only refers to your _fetchProducts() method, which I guess refers to the logger line in your catch block. Please share the stacktrace of the caught exception by adding the stacktrace to your catch block like this: } catch(e, stacktrace) { and share that stacktrace. And a way to understand to which line the stacktrace will refer to in your fetchProducts() method. Best with a screenshot with the line numbers.

@dshukertjr dshukertjr added the postgrest This issue or pull request is related to postgrest label Mar 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working postgrest This issue or pull request is related to postgrest
Projects
None yet
Development

No branches or pull requests

3 participants