Skip to content

Query Keys ​

In fquery_core, a query is uniquely identified by its QueryKey.

At its core, a QueryKey wraps a List<Object?> (also aliased as RawQueryKey). It supports primitives, nested lists, and map structures.

dart
QueryKey(['todos']);
QueryKey(['todos', 42]);
QueryKey(['todos', {'status': 'completed', 'page': 1}]);

Deep Collection Equality ​

Unlike basic object equality (which compares instances by identity), fquery_core compares query keys using deep collection equality via DeepCollectionEquality.

This means:

  1. Two different list instances with identical contents evaluate as equal:
    dart
    QueryKey(['todos', 1]) == QueryKey(['todos', 1]); // true
  2. Nested maps are compared by their key/value entries, regardless of key insertion order:
    dart
    final k1 = QueryKey(['posts', {'id': 1, 'tag': 'news'}]);
    final k2 = QueryKey(['posts', {'tag': 'news', 'id': 1}]);
    
    print(k1 == k2); // true!

Prefix vs Exact Matching ​

When performing cache operations like invalidateQueries and removeQueries, matching is hierarchical by default:

dart
// Key hierarchy:
['todos']
['todos', 'detail', 1]
['todos', 'detail', 2]
['users']

// Prefix match: cache.invalidateQueries(['todos'])
// -> Matches ['todos'], ['todos', 'detail', 1], and ['todos', 'detail', 2]

// Exact match: cache.invalidateQueries(['todos'], exact: true)
// -> Matches ONLY ['todos']

Best Practices for Keys ​

  • Make keys serializable: Query keys should consist of JSON-encodable types (String, int, double, bool, List, Map).
  • Structure hierarchically: Place general namespaces first, followed by filters, identifiers, or parameter maps:
    dart
    ['items', 'list', {'filter': 'active', 'sort': 'desc'}]
    ['items', 'detail', itemId]
  • Include all dependencies: If your queryFn uses an ID or a filter variable, that variable must be included in the QueryKey:
    dart
    // BAD: queryFn uses userId, but key is static
    QueryObserver(queryKey: QueryKey(['profile']), queryFn: () => getProfile(userId));
    
    // GOOD: key changes whenever userId changes
    QueryObserver(queryKey: QueryKey(['profile', userId]), queryFn: () => getProfile(userId));

Released under the MIT License.