基於 Flutter+Dart 聊天例項 | Flutter 仿微信介面聊天室

xiaoyan2017發表於2020-05-13

1、專案介紹

Flutter是目前比較流行的跨平臺開發技術,憑藉其出色的效能獲得很多前端技術愛好者的關注,比如阿里閒魚美團騰訊等大公司都有投入相關案例生產使用。
flutter_chatroom專案是基於Flutter+Dart+chewie+photo_view+image_picker等技術開發的跨平臺仿微信app聊天介面應用,實現了訊息/表情傳送、圖片預覽、長按選單、紅包/小視訊/朋友圈等功能。
022360截圖20200512003659242.png

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字型圖示庫

001360截圖20200512002407906.png

003360截圖20200512002631530.png

004360截圖20200512002755155.png

005360截圖20200512002840849.png

007360截圖20200512002934978.png

008360截圖20200512003004490.png

009360截圖20200512003023266.png

011360截圖20200512003108139.png

014360截圖20200512003208370.png

016360截圖20200512003322336.png

018360截圖20200512003422368.png

019360截圖20200512003435098.png

021360截圖20200512003604679.png

023360截圖20200512003901929.png

026360截圖20200512004446202.png

025360截圖20200512004305675.png

029360截圖20200512004708377.png

031360截圖20200512005508992.png

鑑於flutter基於dart語言,需要安裝Dart Sdk / Flutter Sdk,至於如何搭建開發環境,可以去官網查閱文件資料

https://flutter.cn/

https://flutterchina.club/

https://pub.flutter-io.cn/

https://www.dartcn.com/

使用vscode編輯器,可先安裝DartFlutterFlutter 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中引入字型
360截圖20200513090806912.png

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紅點/圓點提示

360截圖20200513091117720.png
如上圖:在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中如何實現長按,並在長按位置彈出選單,類似微信訊息長按彈窗效果;

360截圖20200513091947231.png
通過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提供了兩個文字框元件:TextFieldTextFormField
本文是使用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聊天頁面功能

360截圖20200513093616798.png

  • 在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桌面聊天

相關文章