V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xiaoyan2017
V2EX  ›  推广

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

  •  
  •   xiaoyan2017 · 2020-05-13 11:59:31 +08:00 · 1220 次点击
    这是一个创建于 1415 天前的主题,其中的信息可能已经有所发展或是发生改变。

    介绍

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

    技术实现

    • 使用技术:Flutter 1.12.13/Dart 2.7.0
    • 视频组件:chewie: ^0.9.7
    • 图片 /拍照:image_picker: ^0.6.6+1
    • 图片预览组件:photo_view: ^0.9.2
    • 弹窗组件:showModalBottomSheet/AlertDialog/SnackBar
    • 本地存储:shared_preferences: ^0.5.7+1
    • 字体图标:阿里 iconfont 字体图标库

    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 聊天页面模块

    • 在 flutter 中实现上图功能,通过 TextField 提供的多行文本框属性 maxLines 就可实现。
    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
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    3 条回复    2020-05-13 12:11:04 +08:00
    Takuron
        1
    Takuron  
       2020-05-13 12:03:44 +08:00 via Android   ❤️ 1
    看了历史发言记录,作者属于无脑全文转载不互动的类型 @Livid
    janxin
        2
    janxin  
       2020-05-13 12:09:52 +08:00
    这个最多算仿,怎么算高仿...

    高仿最起码看起来像吧...
    janxin
        3
    janxin  
       2020-05-13 12:11:04 +08:00   ❤️ 1
    @Livid 根据发帖记录看起来是来做 SEO 的...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   996 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:10 · PVG 06:10 · LAX 15:10 · JFK 18:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.