home_page.dart 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import 'package:agora_chat_demo/models/config.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:agora_chat_sdk/agora_chat_sdk.dart';
  4. class HomePage extends StatefulWidget {
  5. const HomePage({Key? key, required this.title}) : super(key: key);
  6. final String title;
  7. @override
  8. State<HomePage> createState() => _HomePageState();
  9. }
  10. class _HomePageState extends State<HomePage> {
  11. ScrollController scrollController = ScrollController();
  12. String? _messageContent, _chatId;
  13. final List<String> _logText = [];
  14. @override
  15. void initState() {
  16. super.initState();
  17. _initSDK();
  18. _addChatListener();
  19. }
  20. @override
  21. void dispose() {
  22. ChatClient.getInstance.chatManager.removeEventHandler("UNIQUE_HANDLER_ID");
  23. super.dispose();
  24. }
  25. @override
  26. Widget build(BuildContext context) {
  27. return Scaffold(
  28. appBar: AppBar(
  29. title: Text(widget.title),
  30. ),
  31. body: Container(
  32. padding: const EdgeInsets.only(left: 10, right: 10),
  33. child: Column(
  34. crossAxisAlignment: CrossAxisAlignment.stretch,
  35. mainAxisSize: MainAxisSize.max,
  36. children: [
  37. const SizedBox(height: 10),
  38. const Text("login userId: ${Config.userId}"),
  39. const Text("agoraToken: ${Config.agoraToken}"),
  40. const SizedBox(height: 10),
  41. Row(
  42. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  43. children: [
  44. Expanded(
  45. flex: 1,
  46. child: TextButton(
  47. onPressed: _signIn,
  48. style: ButtonStyle(
  49. foregroundColor: MaterialStateProperty.all(Colors.white),
  50. backgroundColor:
  51. MaterialStateProperty.all(Colors.lightBlue),
  52. ),
  53. child: const Text("SIGN IN"),
  54. ),
  55. ),
  56. const SizedBox(width: 10),
  57. Expanded(
  58. child: TextButton(
  59. onPressed: _signOut,
  60. style: ButtonStyle(
  61. foregroundColor: MaterialStateProperty.all(Colors.white),
  62. backgroundColor:
  63. MaterialStateProperty.all(Colors.lightBlue),
  64. ),
  65. child: const Text("SIGN OUT"),
  66. ),
  67. ),
  68. ],
  69. ),
  70. const SizedBox(height: 10),
  71. TextField(
  72. decoration: const InputDecoration(
  73. hintText: "Enter recipient's userId",
  74. ),
  75. onChanged: (chatId) => _chatId = chatId,
  76. ),
  77. TextField(
  78. decoration: const InputDecoration(
  79. hintText: "Enter message",
  80. ),
  81. onChanged: (msg) => _messageContent = msg,
  82. ),
  83. const SizedBox(height: 10),
  84. TextButton(
  85. onPressed: _sendMessage,
  86. style: ButtonStyle(
  87. foregroundColor: MaterialStateProperty.all(Colors.white),
  88. backgroundColor: MaterialStateProperty.all(Colors.lightBlue),
  89. ),
  90. child: const Text("SEND TEXT"),
  91. ),
  92. Flexible(
  93. child: ListView.builder(
  94. controller: scrollController,
  95. itemBuilder: (_, index) {
  96. return Text(_logText[index]);
  97. },
  98. itemCount: _logText.length,
  99. ),
  100. ),
  101. ],
  102. ),
  103. ),
  104. );
  105. }
  106. void _initSDK() async {
  107. ChatOptions options = ChatOptions(
  108. appKey: Config.appKey,
  109. autoLogin: false,
  110. );
  111. await ChatClient.getInstance.init(options);
  112. }
  113. void _addChatListener() {
  114. ChatClient.getInstance.chatManager.addEventHandler(
  115. "UNIQUE_HANDLER_ID",
  116. ChatEventHandler(onMessagesReceived: onMessagesReceived),
  117. );
  118. }
  119. void _signIn() async {
  120. try {
  121. await ChatClient.getInstance.loginWithAgoraToken(
  122. Config.userId,
  123. Config.agoraToken,
  124. );
  125. _addLogToConsole("login succeed, userId: ${Config.userId}");
  126. } on ChatError catch (e) {
  127. _addLogToConsole("login failed, code: ${e.code}, desc: ${e.description}");
  128. }
  129. }
  130. void _signOut() async {
  131. try {
  132. await ChatClient.getInstance.logout(true);
  133. _addLogToConsole("sign out succeed");
  134. } on ChatError catch (e) {
  135. _addLogToConsole(
  136. "sign out failed, code: ${e.code}, desc: ${e.description}");
  137. }
  138. }
  139. void _sendMessage() async {
  140. if (_chatId == null || _messageContent == null) {
  141. _addLogToConsole("single chat id or message content is null");
  142. return;
  143. }
  144. var msg = ChatMessage.createTxtSendMessage(
  145. targetId: _chatId!,
  146. content: _messageContent!,
  147. );
  148. // msg.setMessageStatusCallBack(MessageStatusCallBack(
  149. // onSuccess: () {
  150. // _addLogToConsole("send message: $_messageContent");
  151. // },
  152. // onError: (e) {
  153. // _addLogToConsole(
  154. // "send message failed, code: ${e.code}, desc: ${e.description}",
  155. // );
  156. // },
  157. // ));
  158. ChatClient.getInstance.chatManager.sendMessage(msg);
  159. }
  160. void onMessagesReceived(List<ChatMessage> messages) {
  161. for (var msg in messages) {
  162. switch (msg.body.type) {
  163. case MessageType.TXT:
  164. {
  165. ChatTextMessageBody body = msg.body as ChatTextMessageBody;
  166. _addLogToConsole(
  167. "receive text message: ${body.content}, from: ${msg.from}",
  168. );
  169. }
  170. break;
  171. case MessageType.IMAGE:
  172. {
  173. _addLogToConsole(
  174. "receive image message, from: ${msg.from}",
  175. );
  176. }
  177. break;
  178. case MessageType.VIDEO:
  179. {
  180. _addLogToConsole(
  181. "receive video message, from: ${msg.from}",
  182. );
  183. }
  184. break;
  185. case MessageType.LOCATION:
  186. {
  187. _addLogToConsole(
  188. "receive location message, from: ${msg.from}",
  189. );
  190. }
  191. break;
  192. case MessageType.VOICE:
  193. {
  194. _addLogToConsole(
  195. "receive voice message, from: ${msg.from}",
  196. );
  197. }
  198. break;
  199. case MessageType.FILE:
  200. {
  201. _addLogToConsole(
  202. "receive image message, from: ${msg.from}",
  203. );
  204. }
  205. break;
  206. case MessageType.CUSTOM:
  207. {
  208. _addLogToConsole(
  209. "receive custom message, from: ${msg.from}",
  210. );
  211. }
  212. break;
  213. case MessageType.CMD:
  214. {}
  215. break;
  216. }
  217. }
  218. }
  219. void _addLogToConsole(String log) {
  220. _logText.add("$_timeString: $log");
  221. setState(() {
  222. scrollController.jumpTo(scrollController.position.maxScrollExtent);
  223. });
  224. }
  225. String get _timeString {
  226. return DateTime.now().toString().split(".").first;
  227. }
  228. }