• Flutter高仿微信-第57篇-添加好友


     Flutter高仿微信系列共59篇,从Flutter客户端、Kotlin客户端、Web服务器、数据库表结构、Xmpp即时通讯服务器、视频通话服务器、腾讯云服务器全面讲解。

     详情请查看

    效果图:

    实现代码:

    /**
     * Author : wangning
     * Email : maoning20080809@163.com
     * Date : 2022/8/11 12:16
     * Description : 添加好友
     */
    Color themeDef = Color(0xffEDEDED);
    
    class AddFriends extends StatelessWidget {
    
      UserBean userBean;
    
      AddFriends({required this.userBean});
    
      @override
      Widget build(BuildContext context) {
        return AddFriendsPage(title: '添加好友', userBean: userBean,);
      }
    }
    
    class AddFriendsPage extends StatefulWidget {
    
      UserBean userBean;
      AddFriendsPage({super.key, required this.title, required this.userBean});
      final String title;
    
      @override
      State createState() => _AddFriendsState();
    }
    
    class _AddFriendsState extends State {
    
      @override
      void initState() {
        super.initState();
    
        _checkAvailable();
      }
    
      //检查状态, 如果不可以,先登录
      void _checkAvailable() async{
    
        var isAvailable = await XmppManager.getInstance().isAvailable();
        if(!isAvailable){
          String account = SpUtils.getString(CommonUtils.LOGIN_ACCOUNT);
          String password = SpUtils.getString(CommonUtils.LOGIN_PASSWORD);
          XmppManager.getInstance().connect(account, password);
        }
      }
    
      bool bCanPress = true;
    
      //添加好友
      void _createRoster(String toAccount) async {
    
        if(!bCanPress){
          return;
        }
        bCanPress = false;
        bool isNetwork = await CommonNetwork.isNetwork();
        if(!isNetwork) {
          CommonUtils.showNetworkError(context);
          return;
        }
    
        var isAvailable = await XmppManager.getInstance().isAvailable();
        LogUtils.d("连接状态:${isAvailable} , ${toAccount}");
        if(!isAvailable){
          _checkAvailable();
          CommonToast.show(context, "添加失败,请重试!");
          return;
        }
        CommonToast.show(context, "请稍后。。。");
        UserBean toUserBean = await UserRepository.getInstance().getUserServer(toAccount);
        if(toUserBean != null){
          UserRepository.getInstance().insertUserLocal(toUserBean);
          String account = SpUtils.getString(CommonUtils.LOGIN_ACCOUNT);
          String addTime = WnDateUtils.getCurrentTime();
    
          //添加好友之前, 先删除
          await ContactsRepository.getInstance().deleteContactsByAccount(account, toAccount);
    
          ContactsBean contactsBean  = ContactsBean();
          contactsBean.fromAccount = account;
          contactsBean.toAccount = toAccount;
          contactsBean.type = ContactsBean.typeRequest;
          contactsBean.addTime = addTime;
          ContactsRepository.getInstance().insertContactsLocal(contactsBean);
          ContactsRepository.getInstance().insertContactsServer(contactsBean);
    
    
          XmppManager.getInstance().createRoster(toAccount);
          //获取对方账号信息
          //String message = "${CommonUtils.CHAT_CONTENT_TYPE_ADD_FRIENDS}${CommonUtils.CHAT_MESSAGE_SPILE}${account}${CommonUtils.CHAT_MESSAGE_SPILE}${addTime}";
    
          ChatSendBean chatSendBean = ChatSendBean();
          chatSendBean.contentType = CommonUtils.TYPE_ADD_FRIENDS;
          chatSendBean.content = account;
          chatSendBean.addTime = addTime;
          String message = jsonEncode(chatSendBean);
    
          _sendMessage(toAccount, message);
          CommonToast.show(context, "添加成功!");
          Navigator.pop(context);
        } else {
          CommonToast.show(context, "添加失败,请重试!");
        }
    
        //2秒后才可以继续点击
        Future.delayed(Duration(seconds: 2), (){
          bCanPress = true;
        });
    
      }
    
      _sendMessage(String toAccount, var message){
        int id = DateTime.now().millisecondsSinceEpoch;
        String account = SpUtils.getString(CommonUtils.LOGIN_ACCOUNT);
        String toJid = toAccount + "@wangning";
        LogUtils.d("添加好友发送消息:${toJid} , ${message}");
        XmppManager.getInstance().sendMessage(toJid, message, "$account", id);
      }
    
      String results = "";//原来的内容是空的
      final TextEditingController controller = TextEditingController(text: "");
    
      @override
      Widget build(BuildContext context) {
    
        return Scaffold(
          appBar: WnAppBar.getAppBar(context, Text("${widget.title}")),
    
          body: Column(
            children: [
              _getAccountWidget(),
              _getAddFriendsWidget(),
            ],
          ),
        );
      }
    
      //显示用户信息控件
      Widget _getAccountWidget(){
        String avatarUrl = widget.userBean.avatar??"";
        return Container(
          height: 140,
          alignment: Alignment.bottomCenter,
          padding: const EdgeInsets.all(10.0),//上下左右都设置边距
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: (){
                  Navigator.push(context, MaterialPageRoute(builder: (context) => CommonImagePreview(fileName : CommonUtils.getReallyImage(avatarUrl), isNetwork: true, defaultUrl: CommonUtils.getDefaultAvatar(),)));
                },
                child: CommonAvatarView.showBaseImage(avatarUrl, 80, 80),
              ),
              SizedBox(width: 12),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("${widget.userBean.nickName}", style: TextStyle(fontSize: 20, color: Colors.black),),
                  Text("账号:${widget.userBean.account}", style: TextStyle(fontSize: 16, color: Colors.black),),
                ],
              ),
            ],
          ),
        );
      }
    
      //添加控件
      Widget _getAddFriendsWidget(){
        return Container(
            padding: const EdgeInsets.all(10.0),//上下左右都设置边距
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MaterialButton(
                  color: Colors.blue,
                  textColor: Colors.white,
                  padding: EdgeInsets.only(left: 28, top: 8, right: 28, bottom: 8),
                  child: Text('添加到通讯录',style: TextStyle(fontSize: 16),),
                  onPressed: () {
                    LogUtils.d("点击  添加到通讯录 ");
                    _createRoster(widget.userBean.account!);
                  },
                )
              ],
            ),
        );
      }
    }

  • 相关阅读:
    ElevenLabs用AI为Sora文生视频模型配音 ,景联文科技提供高质量真人音频数据集助力生成逼真音效
    云计算技术的选择题Hadoop的知识点
    Day16--购物车页面-演示效果并创建编译模式
    基于Python实现语法分析
    『论文阅读|利用深度学习在热图像中实现无人机目标检测』
    rust运算
    Policy Gradient梯度策略(PG)
    建模杂谈系列182 FuncDict2_模式设计
    c++ 学习 之 运算符重载
    java: 错误:无效的源发行版
  • 原文地址:https://blog.csdn.net/maoning20080808/article/details/128051241