Why Choose kata_cx?

The kata_cx Flutter package provides a headless client for the Kata CX Dashboard chat service. It handles networking, authentication, message streaming, and CSAT (Customer Satisfaction) surveys without imposing any UI. This makes it ideal when you want to keep UI concerns separate from communication logic or when you need a lightweight, platform‑agnostic chat backend for iOS, Android, and Web.

When to Use This Package

  • Your app needs real‑time chat or messaging without building the networking layer from scratch.
  • You prefer a headless solution so you can design custom UI widgets.
  • You follow a clean architecture and want the chat client to live behind a service or repository boundary.
  • You need built‑in support for CSAT surveys after a conversation ends.

Installation

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

Code
flutter pub add kata_cx

After the command finishes, run flutter pub get to fetch the dependency.

Basic Setup

Place all Kata CX interactions inside a dedicated service class. This keeps the rest of your codebase UI‑agnostic.

Code
import 'package:kata_cx/kata_cx.dart';

class KataCxService {
  final KataCxClient _client;

  KataCxService({required String apiKey})
      : _client = KataCxClient(apiKey: apiKey);

  /// Initialize the client – call this once, e.g., in your app's start‑up logic.
  Future init() async {
    await _client.connect();
  }

  /// Send a chat message and return the server‑generated ID.
  Future sendMessage(String conversationId, String text) async {
    final response = await _client.sendMessage(
      conversationId: conversationId,
      message: text,
    );
    return response.messageId;
  }

  /// Stream incoming replies for a given conversation.
  Stream replyStream(String conversationId) {
    return _client.replyStream(conversationId);
  }

  /// Trigger the CSAT survey for a finished conversation.
  Future runCsat(String conversationId) async {
    await _client.startCsatSurvey(conversationId);
  }
}

Replace apiKey with the key you obtain from the Kata CX dashboard.

Using the Service in a Widget

Below is a minimal example that demonstrates sending a message, listening for replies, and launching a CSAT survey when the user taps a button.

Dart / Flutter
import 'package:flutter/material.dart';
import 'kata_cx_service.dart'; // Assume the service file is named kata_cx_service.dart

class ChatScreen extends StatefulWidget {
  final String conversationId;
  const ChatScreen({Key? key, required this.conversationId}) : super(key: key);

  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State {
  late final KataCxService _kataService;
  final TextEditingController _controller = TextEditingController();
  final List _messages = [];

  @override
  void initState() {
    super.initState();
    _kataService = KataCxService(apiKey: 'YOUR_API_KEY');
    _kataService.init();
    _listenToReplies();
  }

  void _listenToReplies() {
    _kataService.replyStream(widget.conversationId).listen((reply) {
      setState(() {
        _messages.add('Bot: ${reply.text}');
      });
    });
  }

  Future _send() async {
    final text = _controller.text.trim();
    if (text.isEmpty) return;
    setState(() {
      _messages.add('Me: $text');
    });
    await _kataService.sendMessage(widget.conversationId, text);
    _controller.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Kata CX Chat')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) => ListTile(
                title: Text(_messages[index]),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: const InputDecoration(
                      hintText: 'Type a message',
                    ),
                    onSubmitted: (_) => _send(),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.send),
                  onPressed: _send,
                ),
              ],
            ),
          ),
          ElevatedButton(
            onPressed: () => _kataService.runCsat(widget.conversationId),
            child: const Text('Finish & Run CSAT'),
          ),
        ],
      ),
    );
  }
}

Tip: Keep the KataCxService instance in a provider (e.g., Provider or Riverpod) so that multiple widgets can share the same connection without re‑initialising the client.

Setup Notes & Best Practices

  • Platform Checks: The package works on iOS, Android, and Web. Verify that any native permissions (e.g., internet access) are declared in AndroidManifest.xml and Info.plist.
  • Error Handling: Wrap all async calls in try / catch and surface user‑friendly messages. The API may throw KataCxException on network failures.
  • Configuration Isolation: Store the API key securely (e.g., using flutter_secure_storage) and inject it via the service constructor rather than hard‑coding.
  • Testing: Mock KataCxClient in unit tests. The package does not ship a mock implementation, so you’ll need to create a fake class that implements the same interface.

Mistakes to Avoid

  • Calling connect() inside every widget build – it should be a one‑time start‑up operation.
  • Mixing UI code directly with KataCxClient calls; this couples your UI to the third‑party API and makes refactoring harder.
  • Ignoring version compatibility – the package APIs may change. Always check the changelog before upgrading.
  • Storing the API key in plain text within the repository. Use environment variables or secure storage.

FAQ

  • Q: Does kata_cx provide UI widgets?
    A: No. It is a headless client that only handles networking and data. You build your own UI on top of the streams and responses it provides.
  • Q: Can I use the package on the web?
    A: Yes. The package is listed under the "Networking and API" category and supports iOS, Android, and Web. Verify that CORS settings on your Kata CX backend allow browser requests.
  • Q: How do I run unit tests without hitting the real API?
    A: Create a mock implementation of KataCxClient that returns predefined responses. Inject the mock via the service constructor during testing.
  • Q: Where can I find the full API reference?
    A: Consult the official package page on pub.dev: https://pub.dev/packages/kata_cx. The README and the generated documentation contain the latest method signatures.

Frequently Asked Questions

Does kata_cx provide UI widgets?

No. It is a headless client that only handles networking and data. You build your own UI on top of the streams and responses it provides.

Can I use the package on the web?

Yes. The package supports iOS, Android, and Web. Verify that CORS settings on your Kata CX backend allow browser requests.

How do I run unit tests without hitting the real API?

Create a mock implementation of KataCxClient that returns predefined responses. Inject the mock via the service constructor during testing.

Where can I find the full API reference?

Consult the official package page on pub.dev: https://pub.dev/packages/kata_cx. The README and generated documentation contain the latest method signatures.