---
url: https://talkjs.com/docs/UI_Components/Flutter
---

# Flutter

Ask a question Copy for LLM [View as Markdown](/docs/UI_Components/Flutter.md)
This guide will help you quickly add TalkJS to your Flutter app and create a chat between two users. It uses TalkJS's [Flutter SDK](/docs/UI_Components/Flutter/), which provides pre-built chat UI widgets for your application.

In the guide we'll walk you through installing TalkJS and creating new users and conversations.

## Prerequisites

To make the most of this guide, you will need:

1. A [TalkJS account](/dashboard/signup/premium/)
2. [Flutter](https://docs.flutter.dev/) (version 3.32.0 or higher)
3. A Flutter app that you will add TalkJS to. If you don't already have one, you can follow the [official guides](https://docs.flutter.dev/get-started/install) to get started.

## Install TalkJS

To add TalkJS to your project, run the following commands in your Flutter project root:

```bash
flutter pub add talkjs_flutter
```

## Android Gradle Config

One of the dependencies for `talkjs_flutter` relies on [desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring).
To enable this, you'll need to update your app's Gradle file at `android/app/build.gradle` as shown below:

```groovy
android {
  defaultConfig {
    // Required when setting minSdkVersion to 20 or lower
    multiDexEnabled true
  }

  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true

    // Sets Java compatibility to Java 8
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.3'
}
```

## Firebase on iOS (optional)

If you intend to use Firebase on your app on iOS, you have to add the following
entry to your `Info.plist` either by editing the file directly or via Xcode:

```
<key>flutter_apns.disable_swizzling</key>
<true/>
```

This is due to the TalkJS Flutter package depending on the `flutter_apns` package,
which by default disables Firebase.
By setting that entry, you ensure that Firebase is enabled and can be used.

## Import TalkJS in your source files

Import TalkJS in the sources where you want the chatbox to live.

```dart
import 'package:talkjs_flutter/talkjs_flutter.dart';
```

## Create a TalkJS session

A session represents a TalkJS [session](/docs/Concepts/Sessions/) and
authenticates your app with TalkJS.
To create a session, you need your app ID from the **Settings** page of your dashboard, and the
current TalkJS user.

```dart
final session = Session(appId: '<APP_ID>');
```

You'll need to replace `<APP_ID>` with your TalkJS App ID. You can find your App ID in the **Settings** tab of the [TalkJS dashboard](/dashboard/login). For this tutorial, we recommend using the App ID for TalkJS's [Test Mode](/docs/Features/Environments/).

## Create a TalkJS user

The first step is to create a TalkJS user.
The user object is used to synchronize user data with TalkJS, so you can display
it inside the chat UI.

```dart
final me = session.getUser(
  id: '123456',
  name: 'Alice',
  email: ['alice@example.com'],
  photoUrl: 'https://talkjs.com/images/avatar-1.jpg',
  welcomeMessage: 'Hey there! How are you? :-)',
);
```

## Set the active TalkJS user to the session

Set the `me` property of your session to
the newly created user:

```dart
session.me = me;
```

## Create a conversation

A conversation happens between two or more users.
So far you have just created one TalkJS user.
Next, you'll create another user to create a conversation with.
For this example, you can use a hard-coded dummy user.

```dart
final other = session.getUser(
  id: '654321',
  name: 'Sebastian',
  email: ['Sebastian@example.com'],
  photoUrl: 'https://talkjs.com/images/avatar-5.jpg',
  welcomeMessage: 'Hey, how can I help?',
);
```

Next, create a conversation.
The `getConversation` method attempts to get the conversation between the two
users if the conversation already exists, or otherwise create a new conversation.
The [Talk.oneOnOneId](/docs/UI_Components/Flutter/Talk_Object/#Talk_oneOnOneId) method computes a conversation ID based on participants' IDs.
Use this method if you want to simply create a conversation between two users.
You may want to create a group conversation or generate a conversation ID
associated with a transaction that happened on your platform, such as a purchase.
You can find how to do that in the documentation of the [conversation ID](/docs/Concepts/Conversations/#the-conversation-id).

Also set the participants of the conversation to the users you created.

```dart
final conversation = session.getConversation(
  id: Talk.oneOnOneId(me.id, other.id),
  participants: {Participant(me), Participant(other)},
);
```

## Create the chatbox in your widget tree

The chatbox is one of the UI types of TalkJS.
A chatbox shows a user's conversation and it allows them to write messages.
You can find more UI types [here](/docs/Features/Chat_UIs/).
To create the chatbox, add the following to your widget tree, which is inside one of the `build` methods in your app.

```dart
ChatBox(
  session: session,
  conversation: conversation,
),
```

That's it. The chatbox should be running on your app now.
Here is the full code for this:

```dart
import 'package:flutter/material.dart';
import 'package:talkjs_flutter/talkjs_flutter.dart';

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    final session = Session(appId: '<APP_ID>');

    final me = session.getUser(
      id: '123456',
      name: 'Alice',
      email: ['alice@example.com'],
      photoUrl: 'https://talkjs.com/images/avatar-1.jpg',
      welcomeMessage: 'Hey there! How are you? :-)',
    );

    session.me = me;

    final other = session.getUser(
      id: '654321',
      name: 'Sebastian',
      email: ['Sebastian@example.com'],
      photoUrl: 'https://talkjs.com/images/avatar-5.jpg',
      welcomeMessage: 'Hey, how can I help?',
    );

    final conversation = session.getConversation(
      id: Talk.oneOnOneId(me.id, other.id),
      participants: {Participant(me), Participant(other)},
    );

    return MaterialApp(
      title: 'TalkJS Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('TalkJS Demo'),
        ),
        body: ChatBox(
          session: session,
          conversation: conversation,
        ),
      ),
    );
  }
}
```

If the code example isn't working even after reloading your app, you can reach out through the TalkJS support chat.

To enable push notifications in your Flutter app, follow the [Flutter guide](/docs/Guides/Flutter/Push_Notifications/?framework=flutter), which shows you
how to set up mobile push notifications on Flutter.

You can find several examples for different use cases in Flutter in the [TalkJS examples repository on GitHub](https://github.com/talkjs/talkjs-examples/tree/master/flutter_sdk).

Check out the reference pages for the [chatbox](/docs/UI_Components/Flutter/Widgets/Chatbox/) and [ConversationList](/docs/UI_Components/Flutter/Widgets/ConversationList/) widgets to see all the properties
they support.

## Add a loading indicator (optional)

You can use the [onLoadingStateChanged](/docs/UI_Components/Flutter/Widgets/Chatbox/#LoadingStateHandler) method for knowing when the chatbox has completed loading.

In this example you're using the `Visibility` widget to either show a `CircularProgressIndicator` and hide the chatbox while the chatbox is loading, or hide the `CircularProgressIndicator` and show the chatbox when the chatbox has completed loading.

```dart
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:talkjs_flutter/talkjs_flutter.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // We're using this variable as our state
  // It's initialized to false, to show a placeholder widget
  // while the ChatBox is loading
  bool chatBoxVisible = false;

  @override
  Widget build(BuildContext context) {
    final session = Session(appId: '<APP_ID>');
    final me = session.getUser(id: '123456', name: 'Alice');
    session.me = me;

    final other = session.getUser(id: '654321', name: 'Sebastian');

    final conversation = session.getConversation(
      id: Talk.oneOnOneId(me.id, other.id),
      participants: {Participant(me), Participant(other)},
    );

    return MaterialApp(
      title: 'TalkJS Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Test TalkJS'),
        ),
        body: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) => Column(
            children: <Widget>[
              // We use Visibility to show or hide the widgets
              Visibility(
                visible: !chatBoxVisible, // Shown when the ChatBox is not visible
                child: SizedBox(
                  width: min(constraints.maxWidth, constraints.maxHeight),
                  height: min(constraints.maxWidth, constraints.maxHeight),
                  // Using CircularProgressIndicator as an example placeholder
                  // while the ChatBox is loading
                  child: CircularProgressIndicator(),
                ),
              ),
              Visibility(
                maintainState: true,     // It is important to set maintainState to true,
                                         // or else the ChatBox will not load
                visible: chatBoxVisible, // Shown when the ChatBox is visible
                child: ConstrainedBox(
                  constraints: constraints, // We need to constrain the size of the widget,
                                            // because the widget must have a valid size,
                                            // even when it is not shown
                  child: ChatBox(
                    session: session,
                    conversation: conversation,
                    onLoadingStateChanged: (state) {
                      // This is the important part:
                      // We're calling setState to force rebuilding the widget tree,
                      // and we set the visibility of the ChatBox according to its loading state
                      setState(() {
                        if (state == LoadingState.loaded) {
                            chatBoxVisible = true;
                        } else {
                            chatBoxVisible = false;
                        }
                      });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
```

## Enable file sharing and voice messages (optional)

To enable file sharing and voice messages when working with Flutter, you need to take some extra steps, as detailed in the following:

- [Enable file sharing on Flutter](/docs/Features/Messages/File_Sharing/#enabling-file-sharing-on-flutter)
- [Use voice messages with a mobile SDK](/docs/Features/Messages/Voice_Messages/#using-voice-messages-with-a-mobile-sdk)

## Customize the UI

You can customize the look, feel, and behavior of your chat UI with HTML and CSS, using the Theme Editor in your TalkJS dashboard. The theme editor for Flutter uses the same theming system as the [Classic JavaScript SDK](/docs/UI_Components/JavaScript/Classic/).

To get started with customization, make sure you have the [Theme Editor enabled](#enable-the-theme-editor), and then follow the [theming guide](/docs/UI_Components/JavaScript/Classic/Themes/?framework=flutter).

### Enable the Theme Editor

To enable the Theme Editor:

1. On the TalkJS dashboard, go to [Project settings](/dashboard/project/settings).
2. In the section **Dashboard settings**, select **Enable UI Theme Editor (Classic SDKs)**, and save your changes.
You can now edit your app's theme directly from the [Themes](/dashboard/themes) section of your dashboard.

## Next steps

In following this guide, you've added powerful user-to-user chat to your Flutter app. You also learned more about the fundamentals of TalkJS, and how it all fits together.

Most importantly, you've built a starting point to try out all the features TalkJS offers. For example, you could edit the UI theme in the [Theme Editor](/docs/UI_Components/JavaScript/Classic/Themes/?framework=flutter), customize your chat with [action buttons](/docs/Guides/JavaScript/Classic/Action_Buttons_Links/) or [HTML panels](/docs/Guides/JavaScript/Classic/HTML_Panels/), or enable [email notifications](/docs/Features/Notifications/Email_Notifications/).

Before you go live, make sure you enable authentication. Authentication keeps your user data secure, by ensuring that only legitimate users can connect to your chat. For details, see: [Authentication](/docs/Features/Security/Authentication/).