Introduction

The tavily_dart Flutter package is a lightweight, null‑safe client for Tavily's search API. It is purpose‑built for Retrieval‑Augmented Generation (RAG) and other LLM‑centric workflows, making it a natural fit for chatbots, knowledge‑base explorers, and search‑as‑you‑type UI components.

When to Use tavily_dart

Consider the tavily_dart client when you need:

  • Real‑time web search results that can be fed to a large language model.
  • A null‑safe, pure‑Dart API that works on all Flutter platforms (iOS, Android, web, desktop).
  • Simple request/response handling without writing your own HTTP boilerplate.

If you require advanced vector stores, on‑premise hosting, or built‑in caching, you may need to combine tavily_dart with other solutions.

Installation

Add the package to your pubspec.yaml using the Flutter CLI:

Code
flutter pub add tavily_dart

Or manually add the dependency and run flutter pub get:

Code
dependencies:
  tavily_dart: ^1.0.0 # check pub.dev for the latest version

Basic Setup

Before you can call the API you need an API key from Tavily. Store it securely, for example using --dart-define at build time:

Code
flutter run --dart-define=TAVILY_API_KEY=your_key_here

In your Dart code you can retrieve the key with String.fromEnvironment:

Code
final apiKey = const String.fromEnvironment('TAVILY_API_KEY');

Beginner‑Friendly Example

The following minimal app demonstrates a searchable text field that queries Tavily and displays the top results.

Dart / Flutter
import 'package:flutter/material.dart';
import 'package:tavily_dart/tavily_dart.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Tavily Search Demo',
      home: const SearchPage(),
    );
  }
}

class SearchPage extends StatefulWidget {
  const SearchPage({Key? key}) : super(key: key);

  @override
  State createState() => _SearchPageState();
}

class _SearchPageState extends State {
  final TavilyClient _client = TavilyClient(
    apiKey: const String.fromEnvironment('TAVILY_API_KEY'),
  );
  final TextEditingController _controller = TextEditingController();
  Future>? _searchFuture;

  void _performSearch() {
    setState(() {
      _searchFuture = _client.search(query: _controller.text, topK: 5);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Tavily Search')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: const InputDecoration(labelText: 'Enter query'),
              onSubmitted: (_) => _performSearch(),
            ),
            const SizedBox(height: 12),
            ElevatedButton(
              onPressed: _performSearch,
              child: const Text('Search'),
            ),
            const SizedBox(height: 20),
            Expanded(
              child: _searchFuture == null
                  ? const Center(child: Text('Enter a query to begin'))
                  : FutureBuilder>(
                      future: _searchFuture,
                      builder: (context, snapshot) {
                        if (snapshot.connectionState == ConnectionState.waiting) {
                          return const Center(child: CircularProgressIndicator());
                        }
                        if (snapshot.hasError) {
                          return Center(child: Text('Error: ${snapshot.error}'));
                        }
                        final results = snapshot.data ?? [];
                        if (results.isEmpty) {
                          return const Center(child: Text('No results found'));
                        }
                        return ListView.builder(
                          itemCount: results.length,
                          itemBuilder: (context, index) {
                            final result = results[index];
                            return ListTile(
                              title: Text(result.title ?? 'Untitled'),
                              subtitle: Text(result.url ?? ''),
                              onTap: () => launchUrl(Uri.parse(result.url!)),
                            );
                          },
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
Tip: The example uses url_launcher to open result links. Add url_launcher to your pubspec if you want that behavior.

Advanced Configuration

The client supports additional parameters such as searchDepth, includeAnswer, and custom metadata. Refer to the official docs for the complete list of options.

Example of enabling answer generation:

Code
await _client.search(
  query: 'Flutter state management',
  topK: 3,
  includeAnswer: true,
);

Common Mistakes to Avoid

  • Hard‑coding the API key: Never commit the key to source control. Use environment variables or secure storage.
  • Ignoring rate limits: Tavily enforces request quotas. Implement exponential back‑off or respect the Retry-After header if you receive a 429 response.
  • Skipping null checks: The API returns nullable fields (e.g., title, url). Guard against null before using them.
  • Assuming built‑in caching: The package does not cache responses. Add your own cache layer if you need offline or repeated‑query performance.

Testing the Integration

Because the client is pure Dart, you can mock TavilyClient in unit tests. Example using mockito:

Code
class MockTavilyClient extends Mock implements TavilyClient {}

void main() {
  final mockClient = MockTavilyClient();
  when(() => mockClient.search(query: any(named: 'query'), topK: any(named: 'topK')))
      .thenAnswer((_) async => [TavilyResult(title: 'Mock', url: 'https://example.com')]);
  // Inject mockClient into your widget or service and verify behavior.
}

Where to Find More Information

For the most up‑to‑date API surface, error codes, and rate‑limit policies, consult the official package page:

Conclusion

The tavily_dart Flutter package offers a clean bridge between Flutter UI code and Tavily's LLM‑friendly search service. By following the installation steps, using the example above, and respecting the noted pitfalls, you can quickly add up‑to‑date, searchable knowledge to any Flutter app.

Frequently Asked Questions

Do I need to enable any special permissions for tavily_dart on mobile platforms?

No additional platform permissions are required because the package uses standard HTTPS requests. However, if you open result URLs with <code>url_launcher</code>, you must add the appropriate intent filters on Android and URL schemes on iOS.

Can I use tavily_dart offline?

The client itself does not provide offline capabilities; it forwards requests to the remote Tavily service. To support offline use you would need to implement your own caching layer and possibly a fallback data source.

How do I handle rate‑limit errors from Tavily?

When the API returns HTTP 429, respect the <code>Retry-After</code> header if present, or implement exponential back‑off before retrying. This logic should be added in your own networking wrapper around <code>TavilyClient</code>.

Is the tavily_dart package compatible with Flutter web?

Yes. The package is pure Dart and does not rely on native code, so it works on all Flutter targets, including web, desktop, and mobile.

Where can I find the full list of query parameters supported by Tavily?

Refer to the official Tavily API documentation linked from the pub.dev page (https://pub.dev/packages/tavily_dart). The package mirrors the API’s parameters, and the generated docs list each optional field.