### Multi-Region Setup Example
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
An example demonstrating how to configure multiple regions for primary, secondary, and fallback hosts.
```dart
final options = ClientOptions(
hosts: [
// Primary region
Host(url: 'us-1.algolia.net', callType: CallType.read),
Host(url: 'us-1.algolia.net', callType: CallType.write),
// Secondary region
Host(url: 'eu-1.algolia.net'),
// Fallback
Host(url: 'fallback.algolia.net'),
],
);
```
--------------------------------
### Multi-Client Application Setup with Algolia
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
This example demonstrates a singleton pattern for managing multiple Algolia clients (SearchClient and InsightsClient) within an application. It centralizes configuration and provides a single point of access.
```dart
class AlgoliaClients {
static final _instance = AlgoliaClients._();
late final SearchClient searchClient;
late final InsightsClient insightsClient;
factory AlgoliaClients() => _instance;
AlgoliaClients._() {
const appId = 'YOUR_APP_ID';
final commonOptions = ClientOptions(
connectTimeout: Duration(seconds: 5),
readTimeout: Duration(seconds: 10),
compression: 'gzip',
logger: _log,
);
searchClient = SearchClient(
appId: appId,
apiKey: 'SEARCH_API_KEY',
options: commonOptions,
);
insightsClient = InsightsClient(
appId: appId,
apiKey: 'INSIGHTS_API_KEY',
options: commonOptions,
region: 'de',
);
}
static void _log(Object? msg) {
developer.log(msg.toString(), level: 800, name: 'algolia');
}
}
// Usage
final clients = AlgoliaClients();
await clients.searchClient.search(...);
```
--------------------------------
### Minimal Algolia SearchClient Setup (Development)
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
This snippet shows the most basic setup for initializing the SearchClient for development purposes. It requires only the application ID and API key.
```dart
void main() {
final client = SearchClient(
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_API_KEY',
);
}
```
--------------------------------
### Recommended Algolia SearchClient Setup (Production)
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
This is the recommended production setup for the SearchClient, including client options for timeouts, custom headers, and a production logger. Ensure to replace 'productionLogger' with your actual logging implementation.
```dart
void main() {
final client = SearchClient(
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_API_KEY',
options: ClientOptions(
connectTimeout: Duration(seconds: 5),
readTimeout: Duration(seconds: 10),
writeTimeout: Duration(seconds: 30),
headers: {
'User-Agent': 'MyApp/1.0',
},
logger: productionLogger,
compression: 'gzip',
),
);
}
void productionLogger(Object? message) {
developer.log(
message.toString(),
level: 800,
name: 'algolia',
);
}
```
--------------------------------
### Install Dependencies and Run Tests with Melos
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md
Use Melos to install project dependencies and execute tests across all packages. Ensure the Dart SDK is installed.
```bash
cd clients/algoliasearch-client-dart
melos bootstrap
melos run test
```
--------------------------------
### GDPR-Compliant Algolia Setup (EU)
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
This setup configures the SearchClient to use EU data centers and initializes an InsightsClient with a specified EU region ('de') for GDPR compliance. Ensure your application's data residency requirements are met.
```dart
final searchClient = SearchClient(
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_API_KEY',
options: ClientOptions(
hosts: [
Host(url: 'algolia.eu-west-1.algolia.net'),
],
),
);
final insightsClient = InsightsClient(
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_API_KEY',
region: 'de', // EU data residency
);
```
--------------------------------
### Usage Example: Search and Track User Interactions
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/insights-client.md
Demonstrates initializing SearchClient and InsightsClient, performing a search with click analytics, and tracking user events like clicks and conversions.
```dart
import 'package:algolia_client_insights/algolia_client_insights.dart';
import 'package:algolia_client_search/algolia_client_search.dart';
void main() async {
// Initialize clients
final searchClient = SearchClient(appId: 'APP_ID', apiKey: 'SEARCH_API_KEY');
final insightsClient = InsightsClient(appId: 'APP_ID', apiKey: 'INSIGHTS_API_KEY');
// Perform a search with click analytics enabled
final searchResponse = await searchClient.search(
searchMethodParams: SearchMethodParams(
requests: [
SearchForHits(
indexName: 'products',
query: 'laptop',
clickAnalytics: true,
hitsPerPage: 20,
),
],
),
);
// Track user interactions
final hits = searchResponse.results.first.hits;
final queryID = searchResponse.results.first.queryID;
await insightsClient.pushEvents(
insightsEvents: InsightsEvents(
events: [
// User clicked on the first result
InsightsEvent(
eventType: 'click',
eventName: 'Product Clicked',
indexName: 'products',
userToken: 'user-123',
objectID: hits[0].objectID,
position: 1,
queryID: queryID,
timestamp: DateTime.now().millisecondsSinceEpoch,
),
// Later, user made a purchase
InsightsEvent(
eventType: 'conversion',
eventName: 'Product Purchased',
indexName: 'products',
userToken: 'user-123',
objectID: hits[0].objectID,
value: 999.99,
timestamp: DateTime.now().millisecondsSinceEpoch,
),
],
),
);
}
```
--------------------------------
### Facets Usage Example
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/types.md
Demonstrates how to iterate through facet data in a search response.
```dart
if (response.facets != null) {
response.facets!.forEach((facetName, facetValues) {
print('Facet: $facetName');
facetValues.forEach((value, count) {
print(' $value: $count');
});
});
}
```
--------------------------------
### High-Performance Algolia SearchClient Setup (Search-Heavy)
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
This configuration is optimized for search-heavy applications, focusing on reduced timeouts for read operations and specifying multiple read hosts for performance and redundancy. It also enables gzip compression.
```dart
final client = SearchClient(
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_API_KEY',
options: ClientOptions(
connectTimeout: Duration(seconds: 2),
readTimeout: Duration(seconds: 5),
writeTimeout: Duration(seconds: 30),
hosts: [
Host(url: 'cdn.algolia.net', callType: CallType.read),
Host(url: 'primary.algolia.net', callType: CallType.read),
Host(url: 'fallback.algolia.net'),
],
compression: 'gzip',
),
);
```
--------------------------------
### Authentication Interceptor Example
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
An example of a custom interceptor that adds an 'Authorization' header to requests.
```dart
class AuthInterceptor extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
options.headers['Authorization'] = 'Bearer ${getToken()}';
handler.next(options);
}
}
```
--------------------------------
### Monorepo Structure Example
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md
Illustrates the monorepo structure for the Dart client, showing the organization of core transport, API clients, and the umbrella package.
```plaintext
packages/
├── client_core/ # Core transport (hand-written)
├── client_search/ # Search API client
├── client_insights/ # Insights API client
├── client_recommend/ # Recommend API client
└── algoliasearch/ # Umbrella package
```
--------------------------------
### Example of Handling AlgoliaNoResponse
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md
Demonstrates how to check if a result is an AlgoliaNoResponse, indicating a successful deletion with no content returned.
```dart
final result = await client.customDelete(
path: '/1/indexes/products',
);
if (result is AlgoliaNoResponse) {
print('Delete successful, no content returned');
}
```
--------------------------------
### Handling UnreachableHostsException
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md
Example of catching and handling UnreachableHostsException, iterating through individual host errors and displaying a support message.
```dart
try {
await client.search(
searchMethodParams: SearchMethodParams(requests: [...]),
);
} on UnreachableHostsException catch (e) {
print('All hosts unreachable');
print('Errors from each host:');
for (final error in e.errors) {
if (error is AlgoliaApiException) {
print(' - API Error ${error.statusCode}: ${error.error}');
} else if (error is AlgoliaTimeoutException) {
print(' - Timeout: ${error.error}');
} else if (error is AlgoliaIOException) {
print(' - I/O Error: ${error.error}');
}
}
print('Support: ${e.message}');
// Implement fallback or alerting
}
```
--------------------------------
### SearchResponses Usage Example
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/types.md
Shows how to process the results from a multi-index search. Iterates through the list of SearchResponse objects to access results for each index.
```dart
final response = await client.search(
searchMethodParams: SearchMethodParams(
requests: [
SearchForHits(indexName: 'products', query: 'laptop'),
SearchForHits(indexName: 'articles', query: 'laptop'),
],
),
);
for (int i = 0; i < response.results.length; i++) {
print('Results for request $i: ${response.results[i].nbHits} hits');
}
```
--------------------------------
### SearchResponse Usage Example
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/types.md
Demonstrates how to use the SearchResponse object after a search operation. Access hit counts, processing time, and iterate through individual hits.
```dart
final response = await client.searchSingleIndex(
indexName: 'products',
searchParams: SearchParamsObject(query: 'laptop', hitsPerPage: 20),
);
print('Found ${response.nbHits} hits');
print('Processing took ${response.processingTimeMS}ms');
for (final hit in response.hits) {
print('${hit.objectID}: ${hit.data}');
}
if (response.queryID != null) {
// Track clicks for this search
print('Query ID: ${response.queryID}');
}
```
--------------------------------
### Install Algolia Search Client for Dart
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md
Add the algoliasearch package to your Dart or Flutter project using the Dart or Flutter CLI.
```bash
# For Dart
dart pub add algoliasearch
# For Flutter
flutter pub add algoliasearch
```
--------------------------------
### Add Algolia Client Core to Flutter Project
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/packages/client_core/README.md
Install the Algolia Client Core package for Flutter projects using the Flutter CLI.
```shell
flutter pub add algolia_client_core
```
--------------------------------
### Hit Data Access Example
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/types.md
Demonstrates how to access data from a Hit object. Retrieve the objectID, specific record attributes from the 'data' map, and check for highlighting information.
```dart
final hit = response.hits.first;
// Get record ID
print(hit.objectID);
// Access record attributes
final name = hit.data['name'];
final price = hit.data['price'];
// Check highlighting
if (hit._highlightResult != null) {
final highlighted = hit._highlightResult!['name'];
// Contains HTML tags: keyword
}
```
--------------------------------
### Get Index Settings
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md
Retrieves all settings for a specified index. Use this method to inspect the current configuration of an index.
```dart
Future getSettings({
required String indexName,
RequestOptions? requestOptions,
})
```
```dart
final settings = await client.getSettings(indexName: 'products');
print(settings.ranking);
```
--------------------------------
### Custom Proxy Configuration for Algolia Client
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
This example demonstrates how to configure a custom HTTP client adapter to route Algolia requests through a proxy. You need to implement the HttpClientAdapter interface with your proxy logic.
```dart
class ProxyAdapter extends HttpClientAdapter {
@override
Future fetch(
RequestOptions options,
Stream? requestStream,
Future Function()? cancelFuture,
) {
// Add proxy configuration
return super.fetch(options, requestStream, cancelFuture);
}
}
final client = SearchClient(
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_API_KEY',
options: ClientOptions(
httpClientAdapter: ProxyAdapter(),
),
);
```
--------------------------------
### Add Algolia Client Core to Dart Project
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/packages/client_core/README.md
Install the Algolia Client Core package for Dart projects using the Dart CLI.
```shell
dart pub add algolia_client_core
```
--------------------------------
### Initialize InsightsClient with Region
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md
Initialize the InsightsClient, specifying a data residency region for compliance. This example sets the region to 'de' for European data residency.
```dart
final client = InsightsClient(
appId: '6BE0576FF4',
apiKey: 'YOUR_INSIGHTS_API_KEY',
region: 'de', // EU data residency
);
```
--------------------------------
### Error Handling with Custom Timeouts
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/request-options.md
Provides an example of how to implement error handling for timeout exceptions and retry requests with a longer timeout if necessary.
```APIDOC
## Error Handling with RequestOptions
Handle timeout errors when using custom timeouts:
```dart
Future searchWithFallback(
String indexName,
String query,
Duration? customTimeout,
) async {
try {
return await client.searchSingleIndex(
indexName: indexName,
searchParams: SearchParamsObject(query: query),
requestOptions: RequestOptions(
readTimeout: customTimeout,
),
);
} on AlgoliaTimeoutException {
print('Request timed out with timeout: $customTimeout');
// Retry with longer timeout
if (customTimeout == null || customTimeout.inSeconds < 30) {
return searchWithFallback(
indexName,
query,
Duration(seconds: 30),
);
}
rethrow;
}
}
```
```
--------------------------------
### Dart Null Safety Examples
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md
Illustrates Dart's sound null safety features, including nullable and non-nullable types, providing defaults with `??`, and safe access with `?.`. Use `!` sparingly.
```dart
// Dart has sound null safety
String? nullable; // Can be null
String nonNull = ''; // Cannot be null
// Use ?? for defaults
final value = nullable ?? 'default';
// Use ?. for safe access
final length = nullable?.length;
// Use ! only when certain (avoid if possible)
final sure = nullable!; // Throws if null
```
--------------------------------
### Handle AlgoliaTimeoutException
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md
Provides an example of how to catch and handle AlgoliaTimeoutException during an API search request. It shows how to access the error details and suggests implementing retry logic with potentially longer timeouts.
```dart
try {
final response = await client.search(
searchMethodParams: SearchMethodParams(requests: [...]),
).timeout(Duration(seconds: 30));
} on AlgoliaTimeoutException catch (e) {
print('Request timed out: ${e.error}');
// Retry with longer timeout or use fallback
}
```
--------------------------------
### Send Custom GET Request
Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/insights-client.md
Sends a custom GET request to the Insights API. Use this for retrieving data via a specific API path and optional query parameters.
```dart
Future