1、專案介紹
Flutter
是目前比較流行的跨平臺開發技術,憑藉其出色的效能獲得很多前端技術愛好者的關注,比如阿里閒魚
,美團
,騰訊
等大公司都有投入相關案例生產使用。
flutter_chatroom專案是基於Flutter+Dart+chewie+photo_view+image_picker
等技術開發的跨平臺仿微信app聊天介面應用,實現了訊息/表情傳送、圖片預覽、長按選單、紅包/小視訊/朋友圈等功能。
2、技術框架
- 使用技術: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基於dart語言,需要安裝Dart Sdk / Flutter Sdk
,至於如何搭建開發環境,可以去官網查閱文件資料
使用vscode編輯器,可先安裝Dart
、Flutter
、Flutter widget snippets
等擴充套件外掛
3、flutter沉浸式狀態列/底部tabbar
flutter中如何實現頂部全背景沉浸式透明狀態列(去掉狀態列黑色半透明背景),去掉右上角banner,可以去看這篇文章
https://segmentfault.com/a/11...
4、flutter圖示元件/IconData自定義封裝元件
- 1、使用系統圖示元件:
Icon(Icons.search)
- 2、使用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)
5、flutter實現badge紅點/圓點提示
如上圖:在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)
6、flutter長按自定義彈窗
- 在flutter中如何實現長按,並在長按位置彈出選單,類似微信訊息長按彈窗效果;
通過InkWell
元件提供的onTapDown
事件獲取座標點實現
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如何實現去掉AlertDialog彈窗大小限制?
可通過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),
),
),
);
}
);
}
7、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; });
},
)
驗證訊息提示則是使用flutter提供的SnackBar實現
// 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);
});
}
}
8、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();},
),
),
- flutter實現滾動聊天資訊到最底部
通過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));
}
行了,基於flutter/dart開發聊天室例項就介紹到這裡,希望能喜歡~~??
最後附上electron桌面端應用例項
electron聊天室|vue+electron-vue仿微信客戶端|electron桌面聊天