skip to Main Content

I have a tables in my supabase database called properties, profile and saved.

The schema for the tables looks like this:

properties
  id int8 (pk),
  created_at timestamptz,
  description text,
  price text,
  address text,
profiles
  id uuid (pk),
  updated_at timestamptz,
  username text,
  email text,
saved
  id uuid (pk),
  created_at timestamptz,
  userid uuid (fk) references id from profile,
  propertyid int8 fk) references id from properties 

I created a CustomLikeButton in the below like_button.dart

import 'package:flutter/material.dart';

class CustomLikeButton extends StatelessWidget {
  final bool isLiked;
  void Function()? onTap;
  CustomLikeButton({super.key, required this.onTap, required this.isLiked});

  @override 
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Icon(
        isLiked ? Icons.favorite : Icons.favorite_border,
        color: isLiked ? Colors.red : Colors.grey,
      )
    );
  }

}

I’m having trouble creating functions that can query the saved table, insert rows into the query table and also delete rows from the query table whenever a property listing is liked or unliked. Any help especially tried and tested will be helpful

2

Answers


  1. Chosen as BEST ANSWER

    these are what my functions look like(They don't work):

    // toggle like
      void toggleLike() async {
        setState(() {
          isLiked = !isLiked;
        });
    
        await updateLikes(widget.saleListingId.toString(), isLiked, email!);
      }
    
      Future<void> updateLikes(String postId, bool isLiked, String email) async {
        final supabase = Supabase.instance.client;
    
        // Fetch the current 'Likes' array from the 'property_for_sale' table for the given postId
        final response = await supabase
            .from('property_for_sale')
            .select('*, likes(*)')
            .eq('id', postId)
            .single();
    
        if (response != null) {
          // Handle error
          print(response);
          return;
        }
    
        List<dynamic> currentLikes = response['likes'] ?? [];
    
        if (isLiked) {
          // If the post is now liked, add the user's email to the 'Likes' field
          currentLikes.add(email);
        } else {
          // If the post is now unliked, remove the user's email from the 'Likes' field
          currentLikes.remove(email);
        }
    
        // Update the 'Likes' field with the modified list
        final updateResponse = await supabase
            .from('property_for_sale')
            .update({'likes': currentLikes})
            .eq('id', postId);
    
        if (updateResponse.error != null) {
          // Handle error
          print(updateResponse.error!.message);
        }
      }
    

  2. Have you tried Postgres Functions and RPC?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search