基于Flutter+Dart+photo_view+image_picker+video_player等技术开发跨平台实战仿微信聊天应用。实现消息发送/表情gif、图片预览、红包/视频号/朋友圈等功能。

 

运用技术

  • 技术框架:Flutter 1.12.13/Dart 2.7.0
  • 视频组件:chewie: ^0.9.7
  • 图片/拍照:image_picker: ^0.6.6+1
  • 图片预览组件:photo_view: ^0.9.2
  • 本地存储:shared_preferences: ^0.5.7+1
  • 字体图标:阿里iconfont字体图标库
/**
 * @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,
    );
  }
}

 

 

 

 

 

 

 

 

 

 

熟悉android开发的可以使用Android Studio开发flutter应用,不熟悉的可以使用vscode开发flutter

使用vscode编辑器开发,可先安装Dart 、Flutter 、Flutter widget snippets等提示扩展插件

◆ flutter中使用Icon图标/阿里iconfont字体图标

  1. 使用系统图标组件: Icon(Icons.search) 
  2. 使用IconData方式: Icon(IconData(0xe60e, fontFamily: 'iconfont'), size: 24.0)

如果使用IconData方式需要先下载阿里图标库字体文件,然后在pubspec.yaml中申明字体

 

为了避免每次重复使用IconData,作了如下简单封装,调用也很简单。

GStyle.iconfont(0xe635, color: Colors.red, size: 14.0)

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

◆ flutter中实现badge红点/圆点提示

在flutter组件中没有如上图圆点提示组件,如是简单封装了badge组件,调用也很简单。

GStyle.badge(0, isdot: true) 

GStyle.badge(13, color: Colors.green, height: 12.0, width: 12.0)

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
        );
    }
}

◆ flutter实现登录/注册表单验证功能

如下代码在文本框末尾实现清空文本框功能

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; });
  },
)
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中通过Timer.periodic来实现验证码60s倒计时

// 60s倒计时
void handleVcode() {
    if(formObj['tel'] == '') {
      _snackbar('手机号不能为空');
    }else if(!Util.checkTel(formObj['tel'])) {
      _snackbar('手机号格式有误');
    }else {
      _countDown();
    }
}
_countDown() {
    if(_validTimer != null) return;
    
    _validTimer = Timer.periodic(Duration(seconds: 1), (t) {
      setState(() {
        if(formObj['time'] > 0) {
          formObj['disabled'] = true;
          formObj['vcodeText'] = '获取验证码(${formObj["time"]--})';
        }else {
          formObj['time'] = 60;
          formObj['vcodeText'] = '获取验证码';
          formObj['disabled'] = false;
          
          _validTimer.cancel();
          _validTimer = null;
        }
      });
    });
}

◆ flutter聊天页面

在flutter中如何实现多行文本框?类似微信聊天输入框,换行并可插入表情。

设置maxLines: null及keyboardType并在外层加个容器限制最小高度即可

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();},
    ),
),

flutter实现滚动聊天信息到最底部

通过ListView里controller的获取最大滚动距离,并通过jumpTo控制滚动。

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));
}

Okey,运用Flutter+Dart开发跨平台仿微信聊天实例项目就介绍到这里,希望能喜欢~~

最后附上两个最近实例项目

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

uniapp仿抖音短视频|uni-app直播聊天实例

 

Logo

致力于链接即构和开发者,提供实时互动和元宇宙领域的前沿洞察、技术分享和丰富的开发者活动,共建实时互动世界。

更多推荐