Flutter
This guide will help you to quickly add the TalkJS Chatbox to your Flutter application.
To get started,
create an account or
login to your dashboard to get your appId
.
Run the following commands in your Flutter project root:
flutter pub add talkjs_flutterflutter pub get
Import TalkJS in the sources where you want the Chatbox to live.
import 'package:talkjs_flutter/talkjs_flutter.dart';
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.
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',photoUrl: 'https://talkjs.com/images/avatar-1.jpg',welcomeMessage: 'Hey there! How are you? :-)',role: 'default',);
Before doing anything else, we MUST set the me
property of our session to
the newly created user.
session.me = me;
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',photoUrl: 'https://talkjs.com/images/avatar-5.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.
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',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',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 above is not working even after reloading your app, you can reach out to us via support chat.
To enable Push Notifications in your Flutter app, we have a guide showing you the one-time setup you'll need to do.
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.
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 loadingbool 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 widgetsVisibility(visible: !chatBoxVisible, // Shown when the ChatBox is not visiblechild: SizedBox(width: min(constraints.maxWidth, constraints.maxHeight),height: min(constraints.maxWidth, constraints.maxHeight),// Using CircularProgressIndicator as an example placeholder// while the ChatBox is loadingchild: CircularProgressIndicator(),),),Visibility(maintainState: true, // It is important to set maintainState to true,// or else the ChatBox will not loadvisible: chatBoxVisible, // Shown when the ChatBox is visiblechild: 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 shownchild: 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 statesetState(() {if (state == LoadingState.loaded) {chatBoxVisible = true;} else {chatBoxVisible = false;}});},),),),],),),),);}}