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:

flutter pub add talkjs_flutter
flutter pub get

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.

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

final session = Session(appId: 'YOUR_APP_ID');

Remember to replace YOUR_APP_ID with the appId found in the TalkJS dashboard.

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.

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

Set the active TalkJS user to the session

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

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.

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

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.

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

ChatBox(
session: session,
conversation: conversation,
),

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

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.
Widget build(BuildContext context) {
final session = Session(appId: 'YOUR_APP_ID');
final me = session.getUser(
id: '123456',
name: 'Alice',
email: ['[email protected]'],
photoUrl: 'https://talkjs.com/images/avatar-1.jpg',
welcomeMessage: 'Hey there! How are you? :-)',
role: 'default',
);
session.me = me;
final other = session.getUser(
id: '654321',
name: 'Sebastian',
email: ['[email protected]'],
photoUrl: 'https://talkjs.com/images/avatar-5.jpg',
welcomeMessage: 'Hey, how can I help?',
role: 'default',
);
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 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.

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);
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;
Widget build(BuildContext context) {
final session = Session(appId: 'YOUR_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;
}
});
},
),
),
),
],
),
),
),
);
}
}