flutter-chatroom是採用基於flutter+dart+chewie+image_picker+photo_view等技術跨端開發仿微信app界面聊天室項目。實現了消息發送/動態gif表情、彈窗、圖片預覽、紅包/朋友圈/小視頻號等功能。html
因爲flutter基於dart語言,須要先安裝Dart Sdk / Flutter Sdk,如何搭建開發環境,不做過多介紹,能夠去官網查閱文檔資料vue
若是使用vscode編輯器開發,可先安裝Dart 、Flutter 、Flutter widget snippets等擴展插件electron
在flutter中如何實現沉浸式透明狀態欄(去掉狀態欄黑色半透明背景),去掉右上角banner提示,能夠去看這篇文章async
http://www.javashuo.com/article/p-yhsrzdhs-gh.html編輯器
方法2 須要先下載阿里圖標庫字體文件,而後在pubspec.yaml中申明字體ide
經過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組件
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 ); } }
/** * @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, ); } }
長按獲取點座標,經過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), ), ), ); } ); }
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中如何實現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跨平臺開發仿微信聊天實例項目就分享到這裏,但願你們能喜歡!😁😁
最後附上基於electron+vue桌面端IM實例