fluttersupabasesupabase-flutter

How to fetch data from Supabase to Flutter App


I have a problem I dont know how to fetch data from Supabase table to my Flutter App. And yes I'm newbie in Supabase ;) ...

Ok, so I have this code:

class _ProductInfoPageState extends State<ProductInfoPage> {
  List<dynamic>? products = []; // Storage for product data

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fetchProducts();
  }

  Future<void> fetchProducts() async {
    var userId = supabase.auth.currentUser!.id;

    if (userId == null) {
      print('user is not logged!');
      return;
    }

    var response = await supabase
        .from('products')
        .select('*')
        .eq('user_id', userId)  // Filter to only include products for the logged-in user
        .order('id', ascending: true)
        .then((data) {
          if (data.error == null && data.data != null) {
            setState(() {
              products = data.data as List<dynamic>;  // Update the list of products
            });
          } else {
            print('Error fetching products: ${data.error?.message}');
          }
        }).catchError((err) {
          print('Caught error: $err');
        });
  }

The problem is that the validator highlights the data.error and data.data elements. I don't know how to get past this. Obviously, I would like to handle exceptions when the data has not been loaded or an error has occurred, but unfortunately these elements do not work. In answer to the question, I tried to ask ChatGPT for advice, but it suggests using .execute at the end of my var response, which is also not recognized by validator.

In dependencies I use:

import 'package:flutter/material.dart';
import 'package:locs_app/main.dart';
import 'package:locs_app/widgets/crud_products.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

supabase instance and my url and anonKey is configured in main.dart

Does anyone know or can someone explain to me why the validator highlights the error and data elements? Or how to replace it to handle exceptions?

Thank you in advance for any advice


Solution

  • You can do it like this :

    Future<void> fetchProducts() async {
      var userId = supabase.auth.currentUser!.id;
    
      if (userId == null) {
        print('user is not logged!');
        return;
      }
    
    
      try {
        final productList = await supabase
           .from('products')
           .select('*')
           .eq('user_id', userId)  
           .order('id', ascending: true)
           .withConverter((list) {
             return (list as List).map((json) => Product.fromJson(json));
            },
        );
        setState(() {
            products = List.from(productList);
        });
      }
      catch(e, stackTrace) {
        print('Caught error: $e');
        print('Stacktrace : $stackTrace');
      }
    }
    

    For better try/catch and error management, take a look at this package : https://pub.dev/packages/fpdart