Flutter

This guide helps you add the TalkJS chatbox chat UI to your Flutter app.

Get your app ID

To get started, create a TalkJS account or login to your dashboard. You can get your app ID from the Settings page of the dashboard.

Install TalkJS

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

1flutter pub add talkjs_flutter

Android Gradle Config

One of the dependencies for talkjs_flutter relies on desugaring. To enable this, you'll need to update your app's Gradle file at android/app/build.gradle as shown below:

1android {
2 defaultConfig {
3 // Required when setting minSdkVersion to 20 or lower
4 multiDexEnabled true
5 }
6
7 compileOptions {
8 // Flag to enable support for the new language APIs
9 coreLibraryDesugaringEnabled true
10
11 // Sets Java compatibility to Java 8
12 sourceCompatibility JavaVersion.VERSION_1_8
13 targetCompatibility JavaVersion.VERSION_1_8
14 }
15}
16
17dependencies {
18 coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.3'
19}

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:

1<key>flutter_apns.disable_swizzling</key>
2<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.

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

Create a TalkJS session

A session represents a TalkJS session 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.

1final 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. For this tutorial, we recommend using the App ID for TalkJS's Test Mode.

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.

1final me = session.getUser(
2 id: '123456',
3 name: 'Alice',
4 email: ['[email protected]'],
5 photoUrl: 'https://talkjs.com/images/avatar-1.jpg',
6 welcomeMessage: 'Hey there! How are you? :-)',
7);

Set the active TalkJS user to the session

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

1session.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.

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

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 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.

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

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

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. To create the chatbox, add the following to your widget tree, which is inside one of the build methods in your app.

1ChatBox(
2 session: session,
3 conversation: conversation,
4),

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

1import 'package:flutter/material.dart';
2import 'package:talkjs_flutter/talkjs_flutter.dart';
3
4void main() {
5 runApp(const MyApp());
6}
7
8class MyApp extends StatelessWidget {
9 const MyApp({Key? key}) : super(key: key);
10
11 // This widget is the root of your application.
12
13 Widget build(BuildContext context) {
14 final session = Session(appId: '<APP_ID>');
15
16 final me = session.getUser(
17 id: '123456',
18 name: 'Alice',
19 email: ['[email protected]'],
20 photoUrl: 'https://talkjs.com/images/avatar-1.jpg',
21 welcomeMessage: 'Hey there! How are you? :-)',
22 );
23
24 session.me = me;
25
26 final other = session.getUser(
27 id: '654321',
28 name: 'Sebastian',
29 email: ['[email protected]'],
30 photoUrl: 'https://talkjs.com/images/avatar-5.jpg',
31 welcomeMessage: 'Hey, how can I help?',
32 );
33
34 final conversation = session.getConversation(
35 id: Talk.oneOnOneId(me.id, other.id),
36 participants: {Participant(me), Participant(other)},
37 );
38
39 return MaterialApp(
40 title: 'TalkJS Demo',
41 home: Scaffold(
42 appBar: AppBar(
43 title: const Text('TalkJS Demo'),
44 ),
45 body: ChatBox(
46 session: session,
47 conversation: conversation,
48 ),
49 ),
50 );
51 }
52}

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

To enable push notifications in your Flutter app, follow the Flutter guide, 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.

Check out the reference pages for the chatbox and ConversationList widgets to see all the properties they support.

Add a loading indicator (optional)

You can use the onLoadingStateChanged 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.

1import 'dart:math';
2
3import 'package:flutter/material.dart';
4import 'package:talkjs_flutter/talkjs_flutter.dart';
5
6void main() {
7 runApp(const MyApp());
8}
9
10class MyApp extends StatefulWidget {
11 const MyApp({Key? key}) : super(key: key);
12
13
14 State<MyApp> createState() => _MyAppState();
15}
16
17class _MyAppState extends State<MyApp> {
18 // We're using this variable as our state
19 // It's initialized to false, to show a placeholder widget
20 // while the ChatBox is loading
21 bool chatBoxVisible = false;
22
23
24 Widget build(BuildContext context) {
25 final session = Session(appId: '<APP_ID>');
26 final me = session.getUser(id: '123456', name: 'Alice');
27 session.me = me;
28
29 final other = session.getUser(id: '654321', name: 'Sebastian');
30
31 final conversation = session.getConversation(
32 id: Talk.oneOnOneId(me.id, other.id),
33 participants: {Participant(me), Participant(other)},
34 );
35
36 return MaterialApp(
37 title: 'TalkJS Demo',
38 home: Scaffold(
39 appBar: AppBar(
40 title: const Text('Test TalkJS'),
41 ),
42 body: LayoutBuilder(
43 builder: (BuildContext context, BoxConstraints constraints) => Column(
44 children: <Widget>[
45 // We use Visibility to show or hide the widgets
46 Visibility(
47 visible: !chatBoxVisible, // Shown when the ChatBox is not visible
48 child: SizedBox(
49 width: min(constraints.maxWidth, constraints.maxHeight),
50 height: min(constraints.maxWidth, constraints.maxHeight),
51 // Using CircularProgressIndicator as an example placeholder
52 // while the ChatBox is loading
53 child: CircularProgressIndicator(),
54 ),
55 ),
56 Visibility(
57 maintainState: true, // It is important to set maintainState to true,
58 // or else the ChatBox will not load
59 visible: chatBoxVisible, // Shown when the ChatBox is visible
60 child: ConstrainedBox(
61 constraints: constraints, // We need to constrain the size of the widget,
62 // because the widget must have a valid size,
63 // even when it is not shown
64 child: ChatBox(
65 session: session,
66 conversation: conversation,
67 onLoadingStateChanged: (state) {
68 // This is the important part:
69 // We're calling setState to force rebuilding the widget tree,
70 // and we set the visibility of the ChatBox according to its loading state
71 setState(() {
72 if (state == LoadingState.loaded) {
73 chatBoxVisible = true;
74 } else {
75 chatBoxVisible = false;
76 }
77 });
78 },
79 ),
80 ),
81 ),
82 ],
83 ),
84 ),
85 ),
86 );
87 }
88}

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:

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 create a new UI theme in the Theme Editor, customize your chat with action buttons or HTML panels, or enable 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.