main.dart 7.6 KB

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