一、項目概述 flutter-chatroom是採用基於flutter+dart+chewie+image_picker+photo_view等技術跨端開發仿微信app界面聊天室項目。實現了消息發送/動態gif表情、彈窗、圖片預覽、紅包/朋友圈/小視頻號等功能。 二、技術框架 編碼/技術:Vscod ...
一、項目概述
flutter-chatroom是採用基於flutter+dart+chewie+image_picker+photo_view等技術跨端開發仿微信app界面聊天室項目。實現了消息發送/動態gif表情、彈窗、圖片預覽、紅包/朋友圈/小視頻號等功能。
二、技術框架
- 編碼/技術: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字體圖標庫
由於flutter基於dart語言,需要先安裝Dart Sdk / Flutter Sdk,如何搭建開發環境,不作過多介紹,可以去官網查閱文檔資料
如果使用vscode編輯器開發,可先安裝Dart 、Flutter 、Flutter widget snippets等擴展插件
◆ 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中申明字體
通過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中紅點/圓點提示
在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控制彈窗寬度
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_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中獲取驗證碼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併在外層加個容器限制最小高度即可。
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跨平臺開發仿微信聊天實例項目就分享到這裡,希望大家能喜歡!