Flutter
This guide helps you add the TalkJS chatbox chat UI to your Flutter app.
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.
To add TalkJS to your project, run the following commands in your Flutter project root:
1flutter pub add talkjs_flutter
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 lower4 multiDexEnabled true5 }67 compileOptions {8 // Flag to enable support for the new language APIs9 coreLibraryDesugaringEnabled true1011 // Sets Java compatibility to Java 812 sourceCompatibility JavaVersion.VERSION_1_813 targetCompatibility JavaVersion.VERSION_1_814 }15}1617dependencies {18 coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.3'19}
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 the sources where you want the chatbox to live.
1import 'package:talkjs_flutter/talkjs_flutter.dart';
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.
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',5 photoUrl: 'https://talkjs.com/images/avatar-1.jpg',6 welcomeMessage: 'Hey there! How are you? :-)',7);
Set the me
property of your session to
the newly created user:
1session.me = me;
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',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);
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';34void main() {5 runApp(const MyApp());6}78class MyApp extends StatelessWidget {9 const MyApp({Key? key}) : super(key: key);1011 // This widget is the root of your application.1213 Widget build(BuildContext context) {14 final session = Session(appId: '<APP_ID>');1516 final me = session.getUser(17 id: '123456',18 name: 'Alice',20 photoUrl: 'https://talkjs.com/images/avatar-1.jpg',21 welcomeMessage: 'Hey there! How are you? :-)',22 );2324 session.me = me;2526 final other = session.getUser(27 id: '654321',28 name: 'Sebastian',30 photoUrl: 'https://talkjs.com/images/avatar-5.jpg',31 welcomeMessage: 'Hey, how can I help?',32 );3334 final conversation = session.getConversation(35 id: Talk.oneOnOneId(me.id, other.id),36 participants: {Participant(me), Participant(other)},37 );3839 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.
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';23import 'package:flutter/material.dart';4import 'package:talkjs_flutter/talkjs_flutter.dart';56void main() {7 runApp(const MyApp());8}910class MyApp extends StatefulWidget {11 const MyApp({Key? key}) : super(key: key);121314 State<MyApp> createState() => _MyAppState();15}1617class _MyAppState extends State<MyApp> {18 // We're using this variable as our state19 // It's initialized to false, to show a placeholder widget20 // while the ChatBox is loading21 bool chatBoxVisible = false;222324 Widget build(BuildContext context) {25 final session = Session(appId: '<APP_ID>');26 final me = session.getUser(id: '123456', name: 'Alice');27 session.me = me;2829 final other = session.getUser(id: '654321', name: 'Sebastian');3031 final conversation = session.getConversation(32 id: Talk.oneOnOneId(me.id, other.id),33 participants: {Participant(me), Participant(other)},34 );3536 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 widgets46 Visibility(47 visible: !chatBoxVisible, // Shown when the ChatBox is not visible48 child: SizedBox(49 width: min(constraints.maxWidth, constraints.maxHeight),50 height: min(constraints.maxWidth, constraints.maxHeight),51 // Using CircularProgressIndicator as an example placeholder52 // while the ChatBox is loading53 child: CircularProgressIndicator(),54 ),55 ),56 Visibility(57 maintainState: true, // It is important to set maintainState to true,58 // or else the ChatBox will not load59 visible: chatBoxVisible, // Shown when the ChatBox is visible60 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 shown64 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 state71 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}
To enable file sharing and voice messages when working with Flutter, you need to take some extra steps, as detailed in the following:
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.