Back

Dynamically building query parameters in Flutter

  • 0
  • Flutter
havoc
23 Feb, 2024, 13:33

Hi! Is there a way to dynamically build the listDocuments query? In the app, the "base" query I have is

TypeScript
      Query.equal('category', 'expenses'), 
      Query.greaterThan('amount', 100),
    ];

   final response = await databases.listDocuments(
      '<DATABASE_ID>',
      '<COLLECTION_ID>',
      query,
    );

I would like to have a checkbox (or a switch) for a select date and then have this date added to the query parameters. How should I do it?

TIA

TL;DR
Developers are discussing dynamically building query parameters in Flutter. One developer suggests adding and removing query parameters using a map and manipulating the map with checkboxes. Another developer is looking for guidance on adding/removing a Query for the date to the base query list on checkbox toggle. **Solution**: One developer suggests using a map for the queries and adding/removing the specific query by key on checkbox toggle. Here's how to do it: ```dart final Map<String, String> query = { 'category': Query.equal('category', 'expenses'), 'amount': Query.greaterThan('amount', 100), }; // Checkbox toggle
Ernest
23 Feb, 2024, 13:36

What about adding/removing the Query for the date to the base query list on checkbox toggle?

havoc
23 Feb, 2024, 13:39

Yes, that's my idea, but how to I add/remove to the query list? What type is Query.equal('date',<date>)?

Ernest
23 Feb, 2024, 13:47

How about just doing

TypeScript
//checkbox enabled
query.add(Query.equal('category', 'expenses')); //This will be the new query to add
//checkbox disabled
query.removeLast();

This method will require a bit of checks to make sure you're not removing any of the base queries. You could use a map for the queries and remove by the query's key. Example

TypeScript
  // Query.method() generates Strings
  final Map<String, String> query = {
    'category': Query.equal('category', 'expenses'),
    'amount': Query.greaterThan('amount', 100),
  };

  //checkbox toggle on
  query.addAll({
    'date': Query.equal('date', ['2024-2-15'])
  });

  //checkbox toggle off
  query.remove('date');

  //To get queries
  query.values.toList();
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more