flutter 高仿微信聊天|flutter/dart 仿微信界面聊天室

2020-05-13 11:59:31 +08:00
 xiaoyan2017

介绍

FlutterChatroom 项目是基于 flutter+dart 技术开发的高仿微信 App 界面聊天实例,基本实现登录 /注册表单验证、消息发送 /动态 gif 表情、弹窗菜单、图片预览、红包 /朋友圈等功能。

技术实现

flutter 主入口页面 main.dart

/**
 * @tpl Flutter 入口页面 | Q:282310962
 */

import 'package:flutter/material.dart';

// 引入公共样式
import 'styles/common.dart';

// 引入底部 Tabbar 页面导航
import 'components/tabbar.dart';

// 引入地址路由
import 'router/routes.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: GStyle.appbarColor,
      ),
      home: TabBarPage(),
      onGenerateRoute: onGenerateRoute,
    );
  }
}

flutter 实现沉浸式状态栏

前段时间就有写过一篇文章介绍 flutter 实现沉浸式状态栏+仿咸鱼底部导航条,可参看这篇文章

Flutter 沉浸式状态栏 /AppBar 导航栏 /仿咸鱼底部凸起导航

flutter 实现自定义阿里 iconfont 图标

IconData 使用方式: Icon(IconData(0xe60e, fontFamily:'iconfont'), size:24.0)

先下载阿里图标库字体文件,然后在 pubspec.yaml 中引入字体

class GStyle {
    // __ 自定义图标
    static iconfont(int codePoint, {double size = 16.0, Color color}) {
        return Icon(
            IconData(codePoint, fontFamily: 'iconfont', matchTextDirection: true),
            size: size,
            color: color,
        );
    }
}

如上:调用也非常简单,可自定义颜色、字体大小;

GStyle.iconfont(0xe635, color: Colors.orange, size: 17.0)

flutter 实现类似微信红点提示

class GStyle {
    // 消息红点
    static badge(int count, {Color color = Colors.red, bool isdot = false, double height = 18.0, double width = 18.0}) {
        final _num = count > 99 ? '···' : count;
        return Container(
            alignment: Alignment.center, height: !isdot ? height : height/2, width: !isdot ? width : width/2,
            decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(100.0)),
            child: !isdot ? Text('$_num', style: TextStyle(color: Colors.white, fontSize: 12.0)) : null
        );
    }
}

如下:支持自定义红点大小、颜色,默认数字超过 99 就...显示;

GStyle.badge(0, isdot:true)

GStyle.badge(13)

GStyle.badge(29, color: Colors.orange, height: 15.0, width: 15.0)

flutter 登录、注册表单

flutter 提供了两个文本框组件:TextField 和 TextFormField, 本文是使用 TextField 实现,并在文本框后添加清空文本框 /密码查看图标

TextField(
  keyboardType: TextInputType.phone,
  controller: TextEditingController.fromValue(TextEditingValue(
    text: formObj['tel'],
    selection: new TextSelection.fromPosition(TextPosition(affinity: TextAffinity.downstream, offset: formObj['tel'].length))
  )),
  decoration: InputDecoration(
    hintText: "请输入手机号",
    isDense: true,
    hintStyle: TextStyle(fontSize: 14.0),
    suffixIcon: Visibility(
      visible: formObj['tel'].isNotEmpty,
      child: InkWell(
        child: GStyle.iconfont(0xe69f, color: Colors.grey, size: 14.0), onTap: () {
          setState(() { formObj['tel'] = ''; });
        }
      ),
    ),
    border: OutlineInputBorder(borderSide: BorderSide.none)
  ),
  onChanged: (val) {
    setState(() { formObj['tel'] = val; });
  },
)

TextField(
  decoration: InputDecoration(
    hintText: "请输入密码",
    isDense: true,
    hintStyle: TextStyle(fontSize: 14.0),
    suffixIcon: InkWell(
      child: Icon(formObj['isObscureText'] ? Icons.visibility_off : Icons.visibility, color: Colors.grey, size: 14.0),
      onTap: () {
        setState(() {
          formObj['isObscureText'] = !formObj['isObscureText'];
        });
      },
    ),
    border: OutlineInputBorder(borderSide: BorderSide.none)
  ),
  obscureText: formObj['isObscureText'],
  onChanged: (val) {
    setState(() { formObj['pwd'] = val; });
  },
)

本地存储使用的是 shared_preferences https://pub.flutter-io.cn/packages/shared_preferences

void handleSubmit() async {
    if(formObj['tel'] == '') {
      _snackbar('手机号不能为空');
    }else if(!Util.checkTel(formObj['tel'])) {
      _snackbar('手机号格式有误');
    }else if(formObj['pwd'] == '') {
      _snackbar('密码不能为空');
    }else {
      // ...接口数据

      // 设置存储信息
      final prefs = await SharedPreferences.getInstance();
      prefs.setBool('hasLogin', true);
      prefs.setInt('user', int.parse(formObj['tel']));
      prefs.setString('token', Util.setToken());

      _snackbar('恭喜你,登录成功', color: Colors.greenAccent[400]);
      Timer(Duration(seconds: 2), (){
        Navigator.pushNamedAndRemoveUntil(context, '/tabbarpage', (route) => route == null);
      });
    }
}

flutter 聊天页面模块

Container(
    margin: GStyle.margin(10.0),
    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(3.0)),
    constraints: BoxConstraints(minHeight: 30.0, maxHeight: 150.0),
    child: TextField(
        maxLines: null,
        keyboardType: TextInputType.multiline,
        decoration: InputDecoration(
          hintStyle: TextStyle(fontSize: 14.0),
          isDense: true,
          contentPadding: EdgeInsets.all(5.0),
          border: OutlineInputBorder(borderSide: BorderSide.none)
        ),
        controller: _textEditingController,
        focusNode: _focusNode,
        onChanged: (val) {
          setState(() {
            editorLastCursor = _textEditingController.selection.baseOffset;
          });
        },
        onTap: () {handleEditorTaped();},
    ),
),

ListView 里有个 controller 属性提供的 jumpTo 方法及_msgController.position.maxScrollExtent 可实现滚动聊天消息至最底部。

ScrollController _msgController = new ScrollController();
...
ListView(
    controller: _msgController,
    padding: EdgeInsets.all(10.0),
    children: renderMsgTpl(),
)

// 滚动消息至聊天底部
void scrollMsgBottom() {
    timer = Timer(Duration(milliseconds: 100), () => _msgController.jumpTo(_msgController.position.maxScrollExtent));
}

ok,基于 flutter 开发聊天实例就分享到这里,希望能有些许帮助!!最后分享个 electron-vue 实例项目

electron 聊天室|vue+electron-vue 仿微信客户端|electron 桌面聊天

作者:xiaoyan2017
链接: https://juejin.im/post/5ebb5c49e51d454de828b0cd
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

1256 次点击
所在节点    推广
3 条回复
Takuron
2020-05-13 12:03:44 +08:00
看了历史发言记录,作者属于无脑全文转载不互动的类型 @Livid
janxin
2020-05-13 12:09:52 +08:00
这个最多算仿,怎么算高仿...

高仿最起码看起来像吧...
janxin
2020-05-13 12:11:04 +08:00
@Livid 根据发帖记录看起来是来做 SEO 的...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/671209

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX