import 'dart:developer'; import 'package:agora_rtc_engine/rtc_engine.dart'; import 'package:agora_rtc_engine_example/config/agora.config.dart' as config; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:permission_handler/permission_handler.dart'; /// MultiChannel Example class StringUid extends StatefulWidget { @override State createState() => _State(); } class _State extends State { late final RtcEngine _engine; String channelId = config.channelId;// 频道id String stringUid = config.stringUid;// 用户id bool isJoined = false; // user 是否加入 频道 TextEditingController? _controller0, _controller1; @override void initState() { super.initState(); _controller0 = TextEditingController(text: channelId); _controller1 = TextEditingController(text: stringUid); this._initEngine(); } @override void dispose() { super.dispose(); _engine.destroy(); } /// 初始化IM _initEngine() async { _engine = await RtcEngine.createWithContext(RtcEngineContext(config.appId)); this._addListeners(); await _engine.setChannelProfile(ChannelProfile.LiveBroadcasting); await _engine.setClientRole(ClientRole.Broadcaster); } _addListeners() { _engine.setEventHandler(RtcEngineEventHandler( joinChannelSuccess: (channel, uid, elapsed) { log('joinChannelSuccess ${channel} ${uid} ${elapsed}'); setState(() { isJoined = true; }); }, leaveChannel: (stats) { log('leaveChannel ${stats.toJson()}'); setState(() { isJoined = false; }); }, )); } _joinChannel() async { if (defaultTargetPlatform == TargetPlatform.android) { await Permission.microphone.request(); } await _engine.joinChannelWithUserAccount( config.token, channelId, stringUid); } _leaveChannel() async { await _engine.leaveChannel(); } /// 获取当前用户信息 _getUserInfo() { _engine.getUserInfoByUserAccount(stringUid).then((userInfo) { log('getUserInfoByUserAccount ${userInfo.toJson()}'); ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('${userInfo.toJson()}'), )); }).catchError((err) { log('getUserInfoByUserAccount ${err}'); }); } @override Widget build(BuildContext context) { return Stack( children: [ Column( children: [ TextField( controller: _controller0, decoration: InputDecoration(hintText: '聊天室'), onChanged: (text) { setState(() { channelId = text; }); }, ), TextField( controller: _controller1, decoration: InputDecoration(hintText: '用户名'), onChanged: (text) { setState(() { stringUid = text; }); }, ), Row( children: [ Expanded( flex: 1, child: ElevatedButton( onPressed: isJoined ? this._leaveChannel : this._joinChannel, child: Text('${isJoined ? 'Leave' : 'Join'} channel'), ), ) ], ), ], ), Align( alignment: Alignment.bottomRight, child: Column( mainAxisSize: MainAxisSize.min, children: [ ElevatedButton( onPressed: this._getUserInfo, child: Text('Get userInfo'), ), ], ), ) ], ); } }