twilio_conversation_sdk 0.0.2 twilio_conversation_sdk: ^0.0.2 copied to clipboard
Twilio Conversation SDK
example/lib/main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:twilio_conversation_sdk/twilio_conversation_sdk.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static var accountSid = 'ACe78f25b098b2a7e1bd7a62e1faa62eb1';
static var apiKey = 'SKd8e02fa8a99bd970be61ec7d5fae1d6b';
static var apiSecret = 'dwJUkXo0mysOXKKAPhG0UduNWf4MKVX8';
static var serviceSid =
'IS8522285db9e3482986f846d12dc31381'; // Conversation Service SID
static var identity = '';
static var participantIdentity = '';
static var pushSid = 'CRb0b18e1d600411634fd4b51e13d8e008';
String? accessToken = "";
final _twilioConversationSdkPlugin = TwilioConversationSdk();
//var conversationId = "CH855f87ea428044ac90b26461afe00990";
//var conversationId = "CH3670dee812a1474a8ab53e1f88da8ce6";
var conversationId = "";
List messages = List.empty(growable: true);
@override
void initState() {
super.initState();
}
void getAccessToken(String accountSid, String apiKey, String apiSecret, String identity,
String serviceSid, String pushSid) async {
accessToken = await _twilioConversationSdkPlugin.generateToken(
accountSid: accountSid,
apiKey: apiKey,
apiSecret: apiSecret,
identity: identity,
serviceSid: serviceSid,
pushSid: pushSid);
final String? resultInitialization = await _twilioConversationSdkPlugin
.initializeConversationClient(accessToken: accessToken!);
if (resultInitialization!.isNotEmpty) {
final String? resultFCM =
await _twilioConversationSdkPlugin.registerFCMToken(fcmToken: "FCM Token Here");
print(resultFCM);
_twilioConversationSdkPlugin.onClientSyncStatusChanged.listen((event) {
print("Client Status Received ${event.toString()}");
if (event['status'] != null) {
if (event['status'] == 2) {
checkOrCreateConversation();
}
}
});
}
setState(() {});
}
checkOrCreateConversation() async {
List conversationList = await _twilioConversationSdkPlugin.getConversations() ?? [];
print("Conversation List $conversationList");
if (conversationList.isNotEmpty) {
bool isParticipantFound = false;
for (Map conversation in conversationList) {
print("Conversation $conversation");
List participantList = await _twilioConversationSdkPlugin.getParticipants(
conversationId: conversation["sid"]) ??
[];
for (Map participant in participantList) {
print("Participant $participant");
if (participant["identity"] == participantIdentity) {
isParticipantFound = true;
conversationId = conversation["sid"];
subscribe();
break;
}
}
if (isParticipantFound) {
break;
}
}
if (!isParticipantFound) {
createConversation();
}
} else {
createConversation();
}
}
unsubscribe() {
_twilioConversationSdkPlugin.unSubscribeToMessageUpdate(
conversationSid: conversationId);
}
subscribe() {
_twilioConversationSdkPlugin.subscribeToMessageUpdate(
conversationSid: conversationId);
_twilioConversationSdkPlugin.onMessageReceived.listen((event) async {
if (event['status'] != null) {
print("Conversation Status Received ${event.toString()}");
if (event['status'] == 3) {
await getAllMessages();
}
} else if (event['author'] != null) {
print("Conversation Message Received ${event.toString()}");
messages.add(event);
}
setState(() {});
});
setState(() {});
}
createConversation() async {
//String timeStamp = DateTime.now().toString();
//String conversationName = "Flutter - $timeStamp";
String conversationName = "$identity-$participantIdentity";
conversationId = (await _twilioConversationSdkPlugin.createConversation(
conversationName: conversationName, identity: identity))!;
print("Result $conversationId");
joinConversation();
addParticipant();
subscribe();
}
joinConversation() async {
String? joinResult = (await _twilioConversationSdkPlugin.joinConversation(
conversationId: conversationId))!;
print("Result $joinResult");
}
sendMessage({bool isSendAttribute = false}) async {
String timeStamp = DateTime.now().toString();
var attribute;
if (isSendAttribute) {
attribute = {
"body": "Message sent on $timeStamp",
"url": "http://www.google.com",
"cardId": timeStamp
};
} else {
attribute = {"body": "Message sent on $timeStamp", "cardId": timeStamp};
}
final String? sendMessage = await _twilioConversationSdkPlugin.sendMessage(
conversationId: conversationId,
message: "Message sent on $timeStamp",
attribute: attribute);
print("Result $sendMessage");
}
getAllMessages() async {
print("Get Message for $conversationId");
messages.clear();
var messageList =
await _twilioConversationSdkPlugin.getMessages(conversationId: conversationId) ??
[];
messages.addAll(messageList);
print("Messages $messages");
setState(() {});
}
addParticipant() async {
final String? addSecondParticipantConversation =
await _twilioConversationSdkPlugin.addParticipant(
conversationId: conversationId, participantName: participantIdentity);
print("Result Second $addSecondParticipantConversation");
unsubscribe();
subscribe();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: [
accessToken!.isEmpty
? TextField(
onChanged: (value) {
identity = value;
},
decoration: const InputDecoration(labelText: 'Enter your identity'),
)
: Container(),
accessToken!.isEmpty
? TextField(
onChanged: (value) {
participantIdentity = value;
},
decoration:
const InputDecoration(labelText: 'Enter participant identity'),
)
: Container(),
accessToken!.isEmpty
? ElevatedButton(
onPressed: () {
if (identity.isNotEmpty) {
getAccessToken(accountSid, apiKey, apiSecret, identity,
serviceSid, pushSid);
}
},
child: Text("Get Access Token"),
)
: Container(),
accessToken!.isNotEmpty
? ElevatedButton(
onPressed: () {
createConversation();
},
child: Text("Create Conversation"),
)
: Container(),
accessToken!.isNotEmpty
? ElevatedButton(
onPressed: () {
sendMessage();
},
child: Text("Send Message"),
)
: Container(),
accessToken!.isNotEmpty
? ElevatedButton(
onPressed: () {
sendMessage(isSendAttribute: true);
},
child: Text("Send Attribute Message"),
)
: Container(),
messages.isNotEmpty
? Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: messages.length,
itemBuilder: (context, index) {
return ListTile(
title: getMessageView(messages[index]["attributes"],
messages[index]["body"], messages[index]["author"]),
);
},
),
)
: Container(),
],
),
),
),
);
}
getMessageView(String attribute, String message, String author) {
if (attribute.contains("url")) {
Map<String, String> attributeModel = Map.castFrom(json.decode(attribute));
//print(valueMap.runtimeType);
if (attributeModel['url'] != null) {
return Container(
height: 100,
width: 50,
color: author == identity ? Colors.blue : Colors.black,
child: Text(
textAlign: author == identity ? TextAlign.end : TextAlign.start,
attributeModel['url']!,
style: TextStyle(color: author == identity ? Colors.white : Colors.white),
),
);
} else {
return Padding(
padding: EdgeInsets.only(
left: author == identity ? 50 : 0, right: author == identity ? 0 : 50),
child: Text(
textAlign: author == identity ? TextAlign.end : TextAlign.start,
message,
style: TextStyle(color: author == identity ? Colors.blue : Colors.black),
),
);
}
} else {
return Padding(
padding: EdgeInsets.only(
left: author == identity ? 50 : 0, right: author == identity ? 0 : 50),
child: Text(
textAlign: author == identity ? TextAlign.end : TextAlign.start,
message,
style: TextStyle(color: author == identity ? Colors.blue : Colors.black),
),
);
}
}
}