home_page.dart 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 appKey: ${Config.appKey}"),
  39. const Text("login userId: ${Config.userId}"),
  40. const Text("agoraToken: ${Config.agoraToken}"),
  41. const SizedBox(height: 10),
  42. Row(
  43. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  44. children: [
  45. Expanded(
  46. flex: 1,
  47. child: TextButton(
  48. onPressed: _signIn,
  49. style: ButtonStyle(
  50. foregroundColor: MaterialStateProperty.all(Colors.white),
  51. backgroundColor:
  52. MaterialStateProperty.all(Colors.lightBlue),
  53. ),
  54. child: const Text("SIGN IN"),
  55. ),
  56. ),
  57. const SizedBox(width: 10),
  58. Expanded(
  59. child: TextButton(
  60. onPressed: _signOut,
  61. style: ButtonStyle(
  62. foregroundColor: MaterialStateProperty.all(Colors.white),
  63. backgroundColor:
  64. MaterialStateProperty.all(Colors.lightBlue),
  65. ),
  66. child: const Text("SIGN OUT"),
  67. ),
  68. ),
  69. ],
  70. ),
  71. const SizedBox(height: 10),
  72. TextField(
  73. decoration: const InputDecoration(
  74. hintText: "Enter recipient's userId",
  75. ),
  76. onChanged: (chatId) => _chatId = chatId,
  77. ),
  78. TextField(
  79. decoration: const InputDecoration(
  80. hintText: "Enter message",
  81. ),
  82. onChanged: (msg) => _messageContent = msg,
  83. ),
  84. const SizedBox(height: 10),
  85. TextButton(
  86. onPressed: _sendMessage,
  87. style: ButtonStyle(
  88. foregroundColor: MaterialStateProperty.all(Colors.white),
  89. backgroundColor: MaterialStateProperty.all(Colors.lightBlue),
  90. ),
  91. child: const Text("SEND TEXT"),
  92. ),
  93. Flexible(
  94. child: ListView.builder(
  95. controller: scrollController,
  96. itemBuilder: (_, index) {
  97. return Text(_logText[index]);
  98. },
  99. itemCount: _logText.length,
  100. ),
  101. ),
  102. ],
  103. ),
  104. ),
  105. );
  106. }
  107. void _initSDK() async {
  108. ChatOptions options = ChatOptions(
  109. appKey: Config.appKey,
  110. autoLogin: false,
  111. );
  112. await ChatClient.getInstance.init(options);
  113. }
  114. void _addChatListener() {
  115. ChatClient.getInstance.chatManager.addEventHandler(
  116. "UNIQUE_HANDLER_ID",
  117. ChatEventHandler(onMessagesReceived: onMessagesReceived),
  118. );
  119. }
  120. /// login
  121. void _signIn() async {
  122. try {
  123. await ChatClient.getInstance.loginWithAgoraToken(
  124. Config.userId,
  125. Config.agoraToken,
  126. );
  127. _addLogToConsole("login succeed, userId: ${Config.userId}");
  128. } on ChatError catch (e) {
  129. _addLogToConsole("login failed, code: ${e.code}, desc: ${e.description}");
  130. }
  131. }
  132. void _signOut() async {
  133. try {
  134. await ChatClient.getInstance.logout(true);
  135. _addLogToConsole("sign out succeed");
  136. } on ChatError catch (e) {
  137. _addLogToConsole(
  138. "sign out failed, code: ${e.code}, desc: ${e.description}");
  139. }
  140. }
  141. void _sendMessage() async {
  142. if (_chatId == null || _messageContent == null) {
  143. _addLogToConsole("single chat id or message content is null");
  144. return;
  145. }
  146. var msg = ChatMessage.createTxtSendMessage(
  147. targetId: _chatId!,
  148. content: _messageContent!,
  149. );
  150. // msg.setMessageStatusCallBack(MessageStatusCallBack(
  151. // onSuccess: () {
  152. // _addLogToConsole("send message: $_messageContent");
  153. // },
  154. // onError: (e) {
  155. // _addLogToConsole(
  156. // "send message failed, code: ${e.code}, desc: ${e.description}",
  157. // );
  158. // },
  159. // ));
  160. ChatClient.getInstance.chatManager.sendMessage(msg);
  161. }
  162. void onMessagesReceived(List<ChatMessage> messages) {
  163. for (var msg in messages) {
  164. switch (msg.body.type) {
  165. case MessageType.TXT:
  166. {
  167. ChatTextMessageBody body = msg.body as ChatTextMessageBody;
  168. _addLogToConsole(
  169. "receive text message: ${body.content}, from: ${msg.from}",
  170. );
  171. }
  172. break;
  173. case MessageType.IMAGE:
  174. {
  175. _addLogToConsole(
  176. "receive image message, from: ${msg.from}",
  177. );
  178. }
  179. break;
  180. case MessageType.VIDEO:
  181. {
  182. _addLogToConsole(
  183. "receive video message, from: ${msg.from}",
  184. );
  185. }
  186. break;
  187. case MessageType.LOCATION:
  188. {
  189. _addLogToConsole(
  190. "receive location message, from: ${msg.from}",
  191. );
  192. }
  193. break;
  194. case MessageType.VOICE:
  195. {
  196. _addLogToConsole(
  197. "receive voice message, from: ${msg.from}",
  198. );
  199. }
  200. break;
  201. case MessageType.FILE:
  202. {
  203. _addLogToConsole(
  204. "receive image message, from: ${msg.from}",
  205. );
  206. }
  207. break;
  208. case MessageType.CUSTOM:
  209. {
  210. _addLogToConsole(
  211. "receive custom message, from: ${msg.from}",
  212. );
  213. }
  214. break;
  215. case MessageType.CMD:
  216. {}
  217. break;
  218. }
  219. }
  220. }
  221. void _addLogToConsole(String log) {
  222. _logText.add("$_timeString: $log");
  223. setState(() {
  224. scrollController.jumpTo(scrollController.position.maxScrollExtent);
  225. });
  226. }
  227. String get _timeString {
  228. return DateTime.now().toString().split(".").first;
  229. }
  230. }