Flutter

This guide will help you to quickly add the TalkJS Chatbox to your Flutter application.

Get your appId

To get started, create an account or login to your dashboard to get your appId.

Install TalkJS

Edit the dependencies section of your project's pubspec.yaml file in your Flutter project as follows:

dependencies:
talkjs_flutter: ^0.2.1

Run the command: flutter pub get on the command line or through Android Studio's Get dependencies button.

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. It also authenticates your app with TalkJS. To create a session, you need your appId gotten from 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 we can display it inside the chat UI.

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

Set the active TalkJS user to the session

Before doing anything else, we MUST set the me property of our session to the newly created user.

session.me = me;

Create a conversation

A conversation happens between two or more people. So far we have just created one TalkJS user. Next, we'll create another user which we'll create a conversation with. For this example, we'll use a hardcoded dummy user.

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

Next, we create a conversation. The getConversation method attempts to get the conversation between the two users if it previously exists or create a new one otherwise. The Talk.oneOnOneId method predictably 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 e.g. a purchase. You can find how to do that here.

We also set the participants of the conversation to the users we created above.

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

One more step to go.

Create the ChatBox in your Widget tree

The Chatbox is one of the UI types of TalkJS. It shows a user's conversation and it allows them to write messages. You can find more UI types here. To create the Chatbox add this to your Widget tree (that is inside one of the build methods in your app).

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

That is 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://demo.talkjs.com/img/alice.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://demo.talkjs.com/img/sebastian.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 above is not working even after reloading your app, you can reach out to us via support chat.

We also have several examples for different use cases in Flutter on our examples repository on GitHub.

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

(optional) Adding a loading indicator

You can use the onLoadingStateChanged method for knowing when the ChatBox has completed loading.

In this example we'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;
}
});
},
),
),
),
],
),
),
),
);
}
}