![f28fb79b87c3cd04dd5bd93d2c90425d.png](https://i-blog.csdnimg.cn/blog_migrate/ba0a23758799b0d6ecf26df8b845f0f2.jpeg)
欢迎关注专栏:里面定期分享Android和Flutter架构技术知识点及解析,还会不断更新的BATJ面试专题,欢迎大家前来探讨交流,如有好的文章也欢迎投稿。
Android架构解析zhuanlan.zhihu.com![e95865081540107d702775aba9564640.png](https://i-blog.csdnimg.cn/blog_migrate/b10bfb506095265c0e66c96e6dafa99d.jpeg)
一、项目概述
flutter-chatroom是采用基于flutter+dart+chewie+image_picker+photo_view等技术跨端开发仿微信app界面聊天室项目。实现了消息发送/动态gif表情、弹窗、图片预览、红包/朋友圈/小视频号等功能。
![7a98055e268add0ded7e466bf1f6417b.png](https://i-blog.csdnimg.cn/blog_migrate/415488fdce0aa9a0ea2d82a1eea48968.png)
二、技术框架
- 编码/技术:Vscode + Flutter 1.12.13/Dart 2.7.0
- 视频组件:chewie: ^0.9.7
- 图片/拍照:image_picker: ^0.6.6+1
- 图片预览组件:photo_view: ^0.9.2
- 弹窗组件:SimpleDialog/showModalBottomSheet/AlertDialog/SnackBar(flutter封装自定义)
- 本地存储:shared_preferences: ^0.5.7+1
- 字体图标:阿里iconfont字体图标库
![e312b8a65c7aa166fd4959e4cc23ed64.png](https://i-blog.csdnimg.cn/blog_migrate/a851b680f6369720c59232f8ed5679ab.png)
![20b904a1248d70081c76342718803864.png](https://i-blog.csdnimg.cn/blog_migrate/32a96dea108d13b4a60d487208ed260b.png)
![b567a4665308ca5742effbc32a480747.png](https://i-blog.csdnimg.cn/blog_migrate/eca6e95548828240feb9bc9a1c56fc4c.png)
![86831fc6382e7fb0a3dd798ee4bba0e6.png](https://i-blog.csdnimg.cn/blog_migrate/48459e897e092b67bb782d5518f0bb63.png)
![2f5791e5fda9ba1c22df7a0dffa32947.png](https://i-blog.csdnimg.cn/blog_migrate/4ba48c925495b561ca1db44892520a15.png)
![a9c21ed803650360ebb37f79d890fbcc.png](https://i-blog.csdnimg.cn/blog_migrate/1a73975d5c74d2e0d9e6ca1555e94f7e.png)
![13201898f279bb2d0c1c67f641f0deba.png](https://i-blog.csdnimg.cn/blog_migrate/abfe4939fc8f6396d297e69b80e59737.png)
![4a7d80dde18d74d186a5d44774bfa2cf.png](https://i-blog.csdnimg.cn/blog_migrate/ca6333ddb705124b5c0bd8a7dd03991d.png)
![6acf3fb16e56d5f1264182e83dd60801.png](https://i-blog.csdnimg.cn/blog_migrate/2bc702be030adc9b280ffe3960915f69.png)
![e465136cf5e54c067ea26e524de3afcc.png](https://i-blog.csdnimg.cn/blog_migrate/e24b8e684e8756f15013628c9e299d26.png)
![37f5325a2470b28dbf1c3983fed54824.png](https://i-blog.csdnimg.cn/blog_migrate/9bddd6cf6b905862e82d15686296f184.png)
![7ba5c06add1a8879a27166806b186340.png](https://i-blog.csdnimg.cn/blog_migrate/dfe549ad3877e359081dcf7a63398c27.png)
![6a8a4c71e33dae248a453188fb93e1d6.png](https://i-blog.csdnimg.cn/blog_migrate/f15899932bf2862d0c6a73c0e5ef1646.jpeg)
![315ea86116011cdaccd45244d9a11292.png](https://i-blog.csdnimg.cn/blog_migrate/178c284f6b8a7d36ce47c2760f84c292.jpeg)
![47aed4cff41ba97afe1547aa1fcdd340.png](https://i-blog.csdnimg.cn/blog_migrate/f6cd98b4a361e7217bc5d14bd7321a55.png)
![027cac858ffc62b63508a2aea5066893.png](https://i-blog.csdnimg.cn/blog_migrate/d13e5541620766ec0213009c46ce892a.png)
![76244bd9eeb2a0f520cea45dede2e69f.png](https://i-blog.csdnimg.cn/blog_migrate/542bfb6996e0bd176d9f1688f2bdde97.jpeg)
![829c0ddd875c1be10afa056d224c35f1.png](https://i-blog.csdnimg.cn/blog_migrate/6d9f054f63fd75493984f2154aaf718f.jpeg)
![f844aff90253133847a5ab85f05f6893.png](https://i-blog.csdnimg.cn/blog_migrate/7736de4789e61a0e77aacc3d9caa3a31.png)
![8ed87013695d6d4e8f22d551d17c5d3d.png](https://i-blog.csdnimg.cn/blog_migrate/7b0b68af44438e1b081fd5791153df41.png)
由于flutter基于dart语言,需要先安装Dart Sdk / Flutter Sdk,如何搭建开发环境,不作过多介绍,可以去官网查阅文档资料https://flutter.cn/https://flutterchina.club/https://pub.flutter-io.cn/https://www.dartcn.com/
如果使用vscode编辑器开发,可先安装Dart 、Flutter 、Flutter widget snippets等扩展插件
![8036d3772a75de158fd7895b1bf6e7d1.png](https://i-blog.csdnimg.cn/blog_migrate/de84dbcf20572192f54207d89f713379.png)
◆ flutter沉浸式状态栏/底部tabbar导航
在flutter中如何实现沉浸式透明状态栏(去掉状态栏黑色半透明背景),去掉右上角banner提示,可以去看这篇文章https://www.cnblogs.com/xiaoyan2017/p/12784076.html◆ flutter中使用字体图标 (阿里iconfont图标)
- 方法1: 使用系统图标组件: Icon(Icons.search)
- 方法2: 使用IconData方式: Icon(IconData(0xe60e, fontFamily: 'iconfont'), size: 24.0)
方法2 需要先下载阿里图标库字体文件,然后在pubspec.yaml中申明字体
![c980c08b3e574aad8548d1aecddb02c5.png](https://i-blog.csdnimg.cn/blog_migrate/74d161b568025e0c35514b00c02aee75.png)
![d355635134d2295b49dedc056f93fc36.png](https://i-blog.csdnimg.cn/blog_migrate/0cdea17eb8e4042b5da04a4d30e2e99b.jpeg)
![a3ec5e054d226e07afbf2f892aefc173.png](https://i-blog.csdnimg.cn/blog_migrate/3b68972d13acba9b02651653bc824a62.png)
通过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中红点/圆点提示
![52db5e04ebbb8ec737da5bc1d61f037e.png](https://i-blog.csdnimg.cn/blog_migrate/3ba23c905ad023b714ac4fe5222cba31.png)
![d9066acbdbd993051c0881d47b095a6a.png](https://i-blog.csdnimg.cn/blog_migrate/72b17e7b3c5fb3a329ce91714b86cb4c.png)
![00b3f447efe0bd06cee376026ffbac1c.png](https://i-blog.csdnimg.cn/blog_migrate/322aa9fa6b83aa56980bed4dd18f0d3c.png)
在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主入口页面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自定义弹窗实现
长按获取点坐标,通过Positioned组件left top属性实现定位,width控制弹窗宽度
![2e9232179c8fb22972612dfb8d69d374.png](https://i-blog.csdnimg.cn/blog_migrate/f6209fbb2b50d329cb49f49428404cb8.png)
InkWell(
splashColor: Colors.grey[200],
child: Container(...),
onTapDown: (TapDownDetails details) {
_globalPositionX = details.globalPosition.dx;
_globalPositionY = details.globalPosition.dy;
},
onLongPress: () {
_showPopupMenu(context);
},
),
// 长按弹窗
double _globalPositionX = 0.0; //长按位置的横坐标
double _globalPositionY = 0.0; //长按位置的纵坐标
void _showPopupMenu(BuildContext context) {
// 确定点击位置在左侧还是右侧
bool isLeft = _globalPositionX > MediaQuery.of(context).size.width/2 ? false : true;
// 确定点击位置在上半屏幕还是下半屏幕
bool isTop = _globalPositionY > MediaQuery.of(context).size.height/2 ? false : true;
showDialog(
context: context,
builder: (context) {
return Stack(
children: <Widget>[
Positioned(
top: isTop ? _globalPositionY : _globalPositionY - 200.0,
left: isLeft ? _globalPositionX : _globalPositionX - 120.0,
width: 120.0,
child: Material(
...
),
)
],
);
}
);
}
flutter中可否去掉弹窗宽高限制?通过SizedBox组件设置宽度,外层包裹布局无限制容器UnconstrainedBox组件
void _showCardPopup(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnconstrainedBox(
constrainedAxis: Axis.vertical,
child: SizedBox(
width: 260,
child: AlertDialog(
content: Container(
...
),
elevation: 0,
contentPadding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
),
),
);
}
);
}
◆ flutter/dart登录、注册表单验证
TextField文本框,右侧清空文本框按钮通过Visibility组件控制
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; });
},
)
// SnackBar提示
final _scaffoldkey = new GlobalKey<ScaffoldState>();
void _snackbar(String title, {Color color}) {
_scaffoldkey.currentState.showSnackBar(SnackBar(
backgroundColor: color ?? Colors.redAccent,
content: Text(title),
duration: Duration(seconds: 1),
));
}
本地存储使用的是 shared_preferenceshttps://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中获取验证码60s倒计时,使用Timer.periodic实现
// 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中如何实现TextField换行文本框(类似微信聊天编辑框),设置 maxLines 属性就能实现多行文本。
不过设置maxLines,文本框有一定高度,这时只需设置maxLines: null及keyboardType并在外层加个容器限制最小高度即可。
![d0cfaea9a7c2a3a308847ee205c2ae43.png](https://i-blog.csdnimg.cn/blog_migrate/0a53dba8c7ebfb124b53f1ef971fba78.png)
![99940f353a80ef935ecf18e3cef89142.png](https://i-blog.csdnimg.cn/blog_migrate/4f573fe2bb2264f38603f880c610302f.png)
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();},
),
),
另外通过文本框focusNode属性可以实现隐藏键盘
FocusNode _focusNode = FocusNode();
...
void clickMsgPanel() {
// 隐藏键盘
_focusNode.unfocus();
setState(() { showFootToolbar = false; });
}
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)); }
ok,基于flutter+dart跨平台开发仿微信聊天实例项目就分享到这里,希望大家能喜欢! <br/>最后附上基于electron+vue桌面端IM实例<br/>https://www.cnblogs.com/xiaoyan2017/p/12169391.html
推荐阅读:
奶盖:Android 开发从新手到架构师,一篇就够!从1到100万年薪的架构成长之路zhuanlan.zhihu.com![4a4848557d43759f094e04dea41a3fd6.png](https://i-blog.csdnimg.cn/blog_migrate/fafcd880c8bcf654dda7e9c6150023d2.jpeg)
![0a19a05406469047352f66f6088a468e.png](https://i-blog.csdnimg.cn/blog_migrate/54a0be18877ffa973e273765223e1cec.jpeg)
原文作者:xiaoyan2017
原文链接:Flutter聊天室|dart+flutter仿微信App界面|flutter聊天实例 - xiaoyan2017 - 博客园