ยทentrepreneur

custom actions and algolia

Actions & Logic

In custom action, I am performing an algolia query but got no results. I checked the Algolia search API logs and found my queries had errors (400, type post). this my code for ustom action

import 'package:algolia/algolia.dart';
import 'dart:convert'; // For JSON encoding

// Initialize Algolia instance
final Algolia algolia = Algolia.init(
  applicationId: 'application id', // Replace with your Algolia App ID
  apiKey:
      'search only api key', // Replace with your Algolia API Key
);

Future<String> performAlgoliaQuery(
  String searchText,
  String? subcategory,
  String? vertical,
  String? childcategory,
  String? brandName,
  String? excludeProductId,
) async {
  try {
    // Initialize query
    AlgoliaQuery query = algolia.index('inventory').query(searchText);

    // Add filters
    List<String> filters = [];
    if (subcategory?.isNotEmpty ?? false)
      filters.add('subcategory:$subcategory');
    if (vertical?.isNotEmpty ?? false) filters.add('vertical:$vertical');
    if (childcategory?.isNotEmpty ?? false)
      filters.add('childcategory:$childcategory');
    if (brandName?.isNotEmpty ?? false) filters.add('brand:$brandName');
    if (excludeProductId?.isNotEmpty ?? false)
      filters.add('NOT objectID:$excludeProductId');

    // Combine filters
    if (filters.isNotEmpty) query = query.setFilters(filters.join(' AND '));

    // Execute query
    AlgoliaQuerySnapshot snapshot = await query.getObjects();

    // Map results to JSON
    List<Map<String, dynamic>> results = snapshot.hits.map((hit) {
      return {
        'objectID': hit.objectID,
        'inventory_name':
            hit.data['inventory_name'] ?? '', // Replace with your field names
        'inventory_price':
            hit.data['inventory_price'] ?? 0, // Replace with your field names
        'inventory_image':
            hit.data['inventory_image'] ?? '' // Replace with your field names
      };
    }).toList();

    // Convert list to JSON string
    String jsonString = jsonEncode(results);
    return jsonString;
  } catch (e, stackTrace) {
    print('Error performing Algolia query: $e\n$stackTrace');
    return jsonEncode([]);
  }
}
What have you tried so far?

I am using ChatGPT, but it got limitations when it comes to problem solving and nothing is mentioned in document

Did you check FlutterFlow's Documentation for this topic?
Yes
1
2 replies