# Ruut Flutter Chat SDK Documentation

A simple and powerful Flutter SDK to integrate real-time chat into your Flutter app using [Ruut](https://github.com/RuutChatCSM/Ruut-SDK). Connect with your visitors instantly and provide exceptional support.

## Overview

The Ruut Flutter Chat SDK allows you to add a fully-featured chat interface to your Flutter app. It supports real-time messaging, file attachments, customizable themes, and offline message storage.

### Key Features

* Real-time messaging with WebSocket support

* File and image attachments

* Customizable UI themes

* Offline message persistence

* Typing indicators

* User avatars and names

* Message status (sending, delivered, read)

* Customer Satisfaction (CSAT) surveys

## Installation

1. **Add Dependency**  
   Add the `ruut_flutter` package to your `pubspec.yaml` file. Check the [latest version](https://pub.dev/packages/ruut_flutter).

   ```
   dependencies:
     ruut_flutter: ^latest_version
   
   ```

2. **Install Dependencies**  
   Run the following command in your terminal:

   ```
   flutter pub get
   
   ```

### Basic Setup

1. **Create an API Channel**  
   Follow the steps [here](https://app.ruut.chat/hc/ruut-help-desk/articles/1750760863-how-to-setup-an-api-inbox-on-ruut) to create an API channel on the Ruut server and get your `inboxIdentifier`.

2. **Implement RuutChat Widget**  
   Add the `RuutChat` widget to your app:

   ```
   import 'package:flutter/material.dart';
   import 'package:ruut_flutter/ruut_chat.dart';
   import 'package:ruut_flutter/data/local/entity/ruut_user.dart';
   
   void main() {
     runApp(MyApp());
   }
   
   class MyApp extends StatelessWidget {
     @override
     Widget build(BuildContext context) {
       return MaterialApp(
         title: 'Ruut Chat Demo',
         home: Scaffold(
           body: RuutChat(
             inboxIdentifier: 'your_inbox_identifier',
             user: RuutUser(
               identifier: 'user_123',
               name: 'John Doe',
               email: 'john@example.com',
             ),
           ),
         ),
       );
     }
   }
   
   ```

   Replace `your_inbox_identifier` with the inbox identifier from your Ruut API channel.

**Note**: The SDK uses [Hive](https://pub.dev/packages/hive) for local storage.

## Configuration

### Required Parameters

* `inboxIdentifier`: Your Ruut inbox identifier (String, required).

### Optional Parameters

Parameter Type Default Description `enablePersistence` `bool` `true` Enables saving messages and conversations to disk for offline access. `user` `RuutUser` `null` Custom user details (e.g., name, email, avatar). `theme` `RuutChatTheme` Default Customizes the chat UI (colors, fonts, icons). `callbacks` `RuutCallbacks` `null` Handles real-time events (e.g., message received, typing started).

### Custom User Setup

```
RuutChat(
  inboxIdentifier: 'your_inbox_identifier',
  user: RuutUser(
    identifier: 'unique_user_id',
    name: 'Jane Doe',
    email: 'jane@example.com',
    avatarUrl: 'https://example.com/avatar.jpg',
    customAttributes: {
      'plan': 'premium',
      'signup_date': '2024-01-01',
    },
  ),
)
```

### Theme Customization

```
RuutChat(
  inboxIdentifier: 'your_inbox_identifier',
  theme: RuutChatTheme(
    primaryColor: Colors.blue,
    backgroundColor: Colors.white,
    inputBackgroundColor: Colors.grey[100],
    userAvatarNameColors: [Colors.black, Colors.white],
    attachmentButtonIcon: Icon(Icons.image_outlined, color: Colors.grey),
  ),
)
```

### Callbacks

Use `RuutCallbacks` to handle real-time events:

```
RuutChat(
  inboxIdentifier: 'your_inbox_identifier',
  callbacks: RuutCallbacks(
    onMessageReceived: (ruutMessage) {
      print('New message: ${ruutMessage.content}');
    },
    onMessageSent: (ruutMessage, echoId) {
      print('Message sent: ${ruutMessage.content}');
    },
    onError: (error) {
      print('Error: ${error.cause}');
    },
    onConversationStartedTyping: () {
      print('Agent is typing...');
    },
    onConversationIsOnline: () {
      print('Agent is online');
    },
  ),
)
```

#### Available Callbacks

Callback Description `onWelcome` Connection established. `onMessageReceived` New message from agent. `onMessageSent` Message sent successfully. `onMessageDelivered` Message delivered to server. `onConversationStartedTyping` Agent started typing. `onConversationStoppedTyping` Agent stopped typing. `onConversationIsOnline` Agent is online. `onConversationIsOffline` Agent is offline. `onError` Error occurred.

## Troubleshooting

### Common Issues

1. **Chat Not Connecting**

   * Verify your `inboxIdentifier` and Ruut server URL.

   * Example:

     ```
     RuutClient.create(
       baseUrl: 'https://app.ruut.chat',
       inboxIdentifier: 'correct_identifier',
     );
     
     ```

2. **File Upload Fails**

   * Check file size limits and network connection.

   * Handle errors:

     ```
     onError: (error) {
       if (error.type == RuutClientExceptionType.SEND_MESSAGE_FAILED) {
         print('Upload failed. Check connection and retry.');
       }
     }
     
     ```

3. **Messages Not Persisting**

   * Ensure `enablePersistence` is set to `true`:

     ```
     RuutChat(
       inboxIdentifier: 'your_inbox_identifier',
       enablePersistence: true,
     )
     
     ```

4. **Theme Not Applied**

   * Verify theme properties:

     ```
     RuutChat(
       theme: RuutChatTheme(
         primaryColor: Colors.blue,
         backgroundColor: Colors.white,
       ),
     )
     
     ```

### Enable Debug Mode

Add debug logging for troubleshooting:

```
void initState() {
  super.initState();
  debugPrint('Ruut Chat initialized');
}
```

### Error Handling

```
RuutChat(
  callbacks: RuutCallbacks(
    onError: (error) {
      switch (error.type) {
        case RuutClientExceptionType.CREATE_CLIENT_FAILED:
          print('Failed to initialize chat');
          break;
        case RuutClientExceptionType.SEND_MESSAGE_FAILED:
          print('Message failed to send');
          break;
        default:
          print('Unknown error: ${error.cause}');
      }
    },
  ),
)
```

If issues persist, contact us at [admin@ruut.chat](mailto:admin@ruut.chat).

## Best Practices

1. **Error Handling**: Implement robust error handling for all callbacks.

2. **User Feedback**: Show loading states and error messages to users.

3. **Performance**: Use pagination for large message histories:

   ```
   RuutChat(
     onEndReachedThreshold: 0.75,
     onEndReached: () async {
       await ruutClient?.loadMessages();
     },
   )
   ```

4. **Security**: Validate user inputs and handle sensitive data securely.

5. **Testing**: Test on various devices and network conditions.

## Updating the SDK

1. **Check for Updates**:

   ```
   flutter pub outdated
   ```

2. **Update Dependencies**:

   ```
   flutter pub upgrade
   ```

3. **Review Changelog**: Check for breaking changes and test after updates.

## Support

* Check example implementations on [GitHub](https://github.com/RuutChatCSM/Ruut-SDK).

* For issues, contact [admin@ruut.chat](mailto:admin@ruut.chat).