import 'package:cached_network_image/cached_network_image.dart'; import 'package:chat/data/UserData.dart'; import 'package:chat/data/constants.dart'; import 'package:chat/generated/i18n.dart'; import 'package:chat/home/MyDialogContent.dart'; import 'package:chat/home/SelectPage.dart'; import 'package:chat/utils/CustomUI.dart'; import 'package:chat/utils/HttpUtil.dart'; import 'package:chat/utils/MessageMgr.dart'; import 'package:chat/utils/screen.dart'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:city_pickers/city_pickers.dart'; import 'package:flutter/services.dart'; import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; import 'package:image_cropper/image_cropper.dart'; import 'package:oktoast/oktoast.dart'; import '../utils/ShadowButton.dart'; import 'package:image_picker/image_picker.dart'; import 'dart:io'; import '../data/UserData.dart'; import '../utils/TokenMgr.dart'; import '../data/WebData.dart'; import 'IndexPage.dart'; import 'UserAgreement.dart'; const double TipLeft = 20; const double BorderLeft = 25; const double LeftTextFontSize = 13; const LetfTextStyle = TextStyle( fontSize: LeftTextFontSize, fontWeight: FontWeight.w600, color: Constants.BlackTextColor); class EditPage extends StatefulWidget { @required final bool isEditPage; EditPage({Key key, this.isEditPage = false}) : super(key: key); _EditPageState createState() => _EditPageState(); } class _EditPageState extends State { //职业 String profession = ''; Set professionId = Set.from([ UserData().basicInfo.occupation == null ? 'Information-Internet' : UserData().basicInfo.occupation ]); //国家 String country = ''; Set countryId = Set.from([ UserData().basicInfo.country == null ? 'Country-VietNam' : 'Country-${UserData().basicInfo.country}' ]); //期待对象 String lovePeople = ''; Set lovePeopleId = Set.from(UserData().basicInfo.hopeObject == null ? ['Indifferent'] : UserData().basicInfo.hopeObject.split(',')); //是否展示社交账号 bool isHiddenSocialAccount = UserData().basicInfo.accountStatus == 1; //昵称 String nickname = UserData().basicInfo.nickName; //约会范围 String dateRange = ''; Set dateRangeId = Set.from(UserData().basicInfo.meetPlace == null ? [UserData().currentCity] : UserData().basicInfo.meetPlace.split(',')); //生日 String birthday = ''; String birthdayId = UserData().basicInfo.birthday == null ? '1995-01-01' : UserData().basicInfo.birthday; //身高数据 String heightStr = ''; String heightId = UserData().basicInfo.height == null ? '0' : UserData().basicInfo.height.toInt().toString(); //体重数据 String weightStr = ''; String weightId = UserData().basicInfo.weight == null ? '0' : UserData().basicInfo.weight.toInt().toString(); //是否同意用户协议 bool isAgree = false; File headFile; bool loadSuccess = false; String wechat = UserData().basicInfo.wechat; String facebook = UserData().basicInfo.facebook; TextEditingController nickNameController = new TextEditingController(text: UserData().basicInfo.nickName); TextEditingController mymsgController = new TextEditingController(text: UserData().basicInfo.ownMsg); TextEditingController wechatController = new TextEditingController(text: UserData().basicInfo.wechat); TextEditingController fbController = new TextEditingController(text: UserData().basicInfo.facebook); initValue() { if (!loadSuccess) { profession = WebData().getProffesionName(professionId.first); if (!widget.isEditPage) { switch (UserData().language) { case LanguageType.English: countryId = Set.from(['Country-UnitedStates']); break; case LanguageType.Vietnamese: countryId = Set.from(['Country-VietNam']); break; case LanguageType.TraditionalChinese: case LanguageType.TraditionalChinese: countryId = Set.from(['Country-China']); break; case LanguageType.Korean: countryId = Set.from(['Country-Korea']); break; case LanguageType.Japanese: countryId = Set.from(['Country-Japan']); break; default: } } country = WebData().getCountry(countryId.first.split('-')[1]); var hopeObject = ''; lovePeopleId.forEach((f) => hopeObject += hopeObject == '' ? f : ',$f'); lovePeople = WebData().getLovePeople(hopeObject); var dateRangeStr = ''; dateRangeId .forEach((f) => dateRangeStr += dateRangeStr == '' ? f : ',$f'); dateRange = WebData().getDateRange(dateRangeStr); birthday = birthdayId; heightStr = (UserData().basicInfo.height == 0.0 || UserData().basicInfo.height == null) ? I18n.of(context).not_show : '${UserData().basicInfo.height.toInt()}CM'; weightStr = (UserData().basicInfo.weight == 0.0 || UserData().basicInfo.weight == null) ? I18n.of(context).not_show : '${UserData().basicInfo.weight.toInt()}KG'; loadSuccess = true; setState(() {}); } } BoxDecoration _getCardDecoration() { return new BoxDecoration( color: Colors.white, border: Border( top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)); } @override void initState() { super.initState(); MessageMgr().on('change_currentcity', changeCurrentcity); print('EditPage initState'); } changeCurrentcity(data) { if (!widget.isEditPage && dateRangeId.length == 0) { var dateRangeStr = ''; dateRangeId = Set.from([UserData().currentCity]); dateRangeId .forEach((f) => dateRangeStr += dateRangeStr == '' ? f : ',$f'); dateRange = WebData().getDateRange(dateRangeStr); setState(() {}); } } @override void dispose() { nickNameController.dispose(); mymsgController.dispose(); MessageMgr().on('change_currentcity', changeCurrentcity); super.dispose(); } _showDialog() { CustomUI.buildOneConfirm( context, I18n.of(context).exit_registration, I18n.of(context).determine, () { HttpUtil().clearCacheData(); Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute( builder: (context) { return IndexPage(); }, ), (route) => route == null); }); } Future _requestPop() { if (!widget.isEditPage) { _showDialog(); } else { Navigator.of(context).pop(); } return new Future.value(false); } @override Widget build(BuildContext context) { initValue(); var keyHeight = MediaQuery.of(context).viewInsets.bottom; if (keyHeight > 0) { UserData().setKeyboardHeight(keyHeight); } Widget appBar = new AppBar( backgroundColor: AppColors.NewAppbarBgColor, title: new Text( widget.isEditPage ? I18n.of(context).edit_information : I18n.of(context).complete_material, textScaleFactor: 1.0, style: TextStyle(color: AppColors.NewAppbarTextColor), ), elevation: 1, leading: CustomUI.buildCustomLeading(context), actions: [ widget.isEditPage ? Container( alignment: Alignment.center, child: new InkWell( child: new Padding( padding: EdgeInsets.only( right: 15, left: 15, top: 10, bottom: 10), child: new Text( I18n.of(context).save, textScaleFactor: 1.0, style: TextStyle(color: Constants.BlueTextColor), ), ), onTap: () { postSettion((data) { showToast(I18n.of(context).successfully_saved); Navigator.of(context).pop(); MessageMgr().emit('update_data', data); }); }, ), ) : Container(), ], centerTitle: true); return WillPopScope( onWillPop: _requestPop, child: Scaffold( backgroundColor: const Color(0xFFEDEDED), body: SafeArea( child: Center( child: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, child: _buildBody(), ), )), appBar: appBar, )); } Widget _buildBody() { List body = [ _buildHeadUrl(), _buildBasicData(context), UserData().isMan() ? Container() : _buildSocialContact(), // _buildHiddenButtom(), // _buildMoreInfo(), _buildCommitButton(), ]; List body2 = [ _buildBasicData(context), _buildSocialContact(), _buildHiddenButtom(), _buildMoreInfo(), ]; return new ListView( children: widget.isEditPage ? body2 : body, ); } Widget _buildCommitButton() { return new Column( children: [ _buildRegisterButton(), _buildAgreement(), ], ); } Widget _buildAgreement() { return InkWell( onTap: () async { Navigator.of(context).push( new MaterialPageRoute( builder: (context) { return UserAgreement(); }, ), ); }, child: Container( margin: EdgeInsets.only(top: 10, bottom: 20, left: 10, right: 10), child: Text( I18n.of(context).agreed_agreement, style: TextStyle(color: Colors.red), textAlign: TextAlign.center, ))); } postSettion(callback) async { if (nickname == null || nickname == "" || nickname.length > 25) { showToast(I18n.of(context).only1_8); return; } if (dateRangeId.length == 0 && UserData().hasLocationPermission) { showToast(I18n.of(context).Please_select_a_resident_city); return; } if (birthdayId == null || birthdayId == '0') { showToast(I18n.of(context).choose_birthday); return; } if (professionId.length == 0) { showToast(I18n.of(context).choose_career); return; } if (countryId.length == 0) { showToast(I18n.of(context).select_program); return; } if (lovePeopleId.length == 0) { showToast(I18n.of(context).choose_lover); return; } if (!UserData().isMan() && (wechat == null || wechat == '') && (facebook == null || facebook == '')) { showToast(I18n.of(context).least_account); return; } var program = ''; var hopeObject = ''; lovePeopleId.forEach((f) => hopeObject += hopeObject == '' ? f : ',$f'); var dateRangeStr = ''; dateRangeId.forEach((f) => dateRangeStr += dateRangeStr == '' ? f : ',$f'); Map data = { "userId": UserData().basicInfo.userId, "nickName": nickname, "birthday": birthdayId, }; data['sign'] = TokenMgr().getSign(data); data["occupation"] = professionId.first; data["program"] = program; data["hopeObject"] = hopeObject; data["height"] = heightId; data['Country'] = countryId.first.split('-')[1]; data["weight"] = weightId; data["ownMsg"] = mymsgController.text.trim(); data["meetPlace"] = dateRangeStr; data['wxAccount'] = wechat; data['fbAccount'] = facebook; data['accountStatus'] = isHiddenSocialAccount ? 1 : 0; data["lat"] = UserData().latitude; data["lng"] = UserData().longitude; try { Response res = await HttpUtil() .post('user/complete/material', data: data, isShowLoading: true); Map resData = res.data; if (resData['code'] == 0) { UserData().basicInfo.ownMsg = mymsgController.text; callback(mymsgController.text); } else { showToast(resData['msg']); } } catch (e) {} } //构建注册按钮 Widget _buildRegisterButton() { Text text = fixedText(I18n.of(context).submit, fontSize: 15, color: Colors.white); LinearGradient gradientColor = new LinearGradient(colors: [ Constants.ConfrimButtonColor, Constants.ConfrimButtonColor, ]); callback() { postSettion((data) async { Navigator.of(context) .pushNamedAndRemoveUntil('/main', (route) => route == null); }); } return new Container( margin: EdgeInsets.only(top: 20), height: 44, width: MediaQuery.of(context).size.width * 0.85, child: ShadowButton().builder(gradientColor, text, callback), ); } //自定义item Widget _bottomBorderBox(String textLeft, String textRight, bool flag, controller, bool isInit, callback, {inputFormatters}) { Widget left = Container( width: 90, margin: EdgeInsets.only(right: 10), child: Text( textLeft, textScaleFactor: 1.0, style: LetfTextStyle, )); Widget right = flag ? Expanded( child: TextField( keyboardAppearance: Brightness.light, controller: controller, style: TextStyle( fontSize: 14, textBaseline: TextBaseline.alphabetic), decoration: InputDecoration( contentPadding: EdgeInsets.zero, hintText: textRight, hintStyle: TextStyle( fontSize: 14, color: Constants.LightGreyTextColor, fontWeight: FontWeight.normal), border: InputBorder.none, ), maxLines: 1, inputFormatters: inputFormatters, onChanged: (str) { if (flag && callback != null) callback(str); }, ), ) : Expanded( child: Text( textRight, textScaleFactor: 1.0, style: TextStyle( fontSize: 14, color: !isInit ? Constants.LightGreyTextColor : Constants.BlackTextColor), ), ); var icon = !flag ? Padding( padding: EdgeInsets.only(right: 7), child: Icon( IconData(0xe63c, fontFamily: 'iconfont'), size: 20.0, color: Color(AppColors.TabIconNormal), )) : Container(); return new InkWell( highlightColor: Colors.transparent, radius: 0.0, onTap: () { if (!flag && callback != null) callback(); }, child: Container( height: 53, margin: EdgeInsets.only(left: BorderLeft, bottom: 0), child: new Row( children: [left, right, icon], ), )); } //下划线 Widget _buildDivider() { return new Container( margin: EdgeInsets.zero, padding: EdgeInsets.zero, height: 1, width: MediaQuery.of(context).size.width, child: new Divider( color: Colors.grey[300], ), ); } //基本数据 Widget _buildBasicData(context) { Widget tip = CustomUI.buildTopTip( BorderLeft, I18n.of(context).basic_information, showStar: true); //选择约会地区 void selectDateRange() async { print(WebData().provinces['China']); Navigator.of(context).push( new MaterialPageRoute( builder: (context) { return SelectPage( mostNum: 1, dataId: dateRangeId, title: I18n.of(context).Resident_city, provinces: UserData().isInChina ? {'China': WebData().provinces['China']} : { 'VietNam': WebData().provinces['VietNam'], }, cities: WebData().cities, isSingle: true, callback: (tempRankId) { if (tempRankId.length == 0) return; dateRangeId = tempRankId.toSet(); if (dateRangeId.length != 0) { dateRange = ''; dateRangeId.forEach((item) { var city = item.split('-'); dateRange += dateRange == '' ? WebData().cities[city[0]][city[1]] : '/${WebData().cities[city[0]][city[1]]}'; }); } Navigator.of(context).pop(); }, ); }, ), ); } //选择生日 void selectDate() async { var locale; switch (UserData().language) { case LanguageType.English: locale = LocaleType.en; break; case LanguageType.Vietnamese: locale = LocaleType.vi; break; case LanguageType.TraditionalChinese: case LanguageType.SimplifiedChinese: locale = LocaleType.zh; break; case LanguageType.Korean: locale = LocaleType.ko; break; case LanguageType.Japanese: locale = LocaleType.jp; break; default: locale = LocaleType.en; } var list = []; if (birthdayId != null) list = birthdayId.split('-'); var nowDate; nowDate = list.length == 3 ? DateTime(int.parse(list[0]), int.parse(list[1]), int.parse(list[2])) : DateTime(1990, 1, 1); DatePicker.showDatePicker(context, showTitleActions: true, minTime: DateTime(1900, 3, 5), maxTime: DateTime(DateTime.now().year - 18, 1, 1), onChanged: (date) {}, onConfirm: (date) { birthday = '${date.year}-${date.month}-${date.day}'; birthdayId = '${date.year}-${date.month}-${date.day}'; setState(() {}); }, currentTime: nowDate, locale: locale); } //选择职业 void selectProfession() async { Navigator.of(context).push( new MaterialPageRoute( builder: (context) { return SelectPage( mostNum: 4, dataId: professionId, provinces: WebData().professionCate, isSingle: true, cities: WebData().professionList, title: I18n.of(context).choose_career, callback: (Set tempRankId) { professionId = tempRankId.toSet(); if (professionId.length != 0) { profession = ''; professionId.forEach((item) { var city = item.split('-'); profession += profession == '' ? WebData().professionList[city[0]][city[1]] : '/${WebData().professionList[city[0]][city[1]]}'; }); } Navigator.of(context).pop(); }, ); }, ), ); } //选择国家 void selectCountry() async { Navigator.of(context).push( new MaterialPageRoute( builder: (context) { return SelectPage( mostNum: 4, dataId: countryId, title: I18n.of(context).country, provinces: {'Country': I18n.of(context).country}, cities: {'Country': WebData().provinces}, isSingle: true, callback: (tempRankId) { countryId = tempRankId.toSet(); print('countryID ${countryId.length}'); if (countryId.length != 0) { country = ''; countryId.forEach((item) { var city = item.split('-'); country += country == '' ? WebData().provinces[city[1]] : '/${WebData().provinces[city[1]]}'; }); } Navigator.of(context).pop(); }, ); }, ), ); } //选择期待对象 void selectLovePeople() { var tempSet = lovePeopleId.toSet(); List actions = [ FlatButton( child: fixedText(I18n.of(context).close), onPressed: () { tempSet.clear(); Navigator.of(context).pop(); }, ), FlatButton( child: fixedText(I18n.of(context).determine), onPressed: () { Navigator.of(context).pop(); setState(() { lovePeopleId = tempSet.toSet(); if (lovePeopleId.length != 0) { lovePeople = ''; lovePeopleId.forEach((k) { lovePeople += (lovePeople == '') ? WebData().loverPeopleMap[k] : ('/' + WebData().loverPeopleMap[k]); }); } }); }, ), ]; //约会节目 showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: new Align( alignment: Alignment.center, child: Text(I18n.of(context).expect_lover), ), content: new MyDialogContent( mostNum: 4, dataMap: WebData().loverPeopleMap, keyList: tempSet, ), contentPadding: EdgeInsets.only(top: 10), actions: actions, ); }); } Widget idItem = new InkWell( highlightColor: Colors.transparent, radius: 0.0, onTap: () {}, child: Container( height: 53, margin: EdgeInsets.only(left: BorderLeft, bottom: 0), child: new Row( children: [ Container( width: 90, margin: EdgeInsets.only(right: 10), child: Text( 'ID', textScaleFactor: 1.0, style: LetfTextStyle, )), Text( UserData().basicInfo.userId.toString(), textScaleFactor: 1.0, style: TextStyle(fontSize: 14, color: Constants.GreyTextColor), ) ], ), )); List basicList = [ widget.isEditPage ? idItem : Container(), _buildDivider(), _bottomBorderBox(I18n.of(context).nickname, I18n.of(context).fill_out, true, nickNameController, true, (str) => nickname = str.trim(), inputFormatters: [ LengthLimitingTextInputFormatter(Constants.NameLength) ]), _buildDivider(), _bottomBorderBox(I18n.of(context).country, country, false, null, countryId.length != 0, selectCountry), _buildDivider(), _bottomBorderBox( I18n.of(context).Resident_city, !UserData().hasLocationPermission ? I18n.of(context).unknown : dateRange, false, null, dateRangeId.length != 0, UserData().hasLocationPermission ? selectDateRange : null), _buildDivider(), _bottomBorderBox(I18n.of(context).birthday, birthday, false, null, birthdayId != null, selectDate), _buildDivider(), _bottomBorderBox(I18n.of(context).job, profession, false, null, professionId.length != 0, selectProfession), // _bottomBorderBox(I18n.of(context).country, dateItem, false, null, // dateItemId.length != 0, selectCountry), _buildDivider(), _bottomBorderBox(I18n.of(context).expect_lover, lovePeople, false, null, lovePeopleId.length != 0, selectLovePeople), ]; Widget basicCard = new Container( color: Colors.white, child: new Column( children: basicList, ), ); return new Column( children: [ tip, basicCard, ], ); } //社交账号 Widget _buildSocialContact() { Widget tip = CustomUI.buildTopTip( BorderLeft, I18n.of(context).social_account, showStar: !UserData().isMan()); List basicList = [ _bottomBorderBox( I18n.of(context).wechat_number, I18n.of(context).fill_out, true, wechatController, true, (str) => wechat = str.trim(), inputFormatters: [ WhitelistingTextInputFormatter(RegExp("^[A-Za-z0-9]+\$")), LengthLimitingTextInputFormatter(20) ]), _buildDivider(), _bottomBorderBox(I18n.of(context).facebook, I18n.of(context).fill_out, true, fbController, true, (str) => facebook = str.trm(), inputFormatters: [ WhitelistingTextInputFormatter(RegExp("^[A-Za-z0-9]+\$")), LengthLimitingTextInputFormatter(20) ]), ]; Widget socialCard = new Container( color: Colors.white, child: new Column( children: basicList, ), ); return new Column( children: [tip, socialCard], ); } Widget _buildHeadUrl() { double width = 95; return Container( color: Colors.white, padding: EdgeInsets.only(top: 20, bottom: 10), child: Column( children: [ InkWell( onTap: () { _sendPicture(); }, child: Container( width: width, height: width, child: ClipRRect( borderRadius: BorderRadius.circular(6.0), child: uploadImageUrl == null ? Image.asset(Constants.DefaultHeadImgUrl, height: width, width: width) // : Image.file(headFile, height: width, width: width), : CachedNetworkImage( imageUrl: uploadImageUrl, placeholder: CustomUI.buildImgLoding, width: width, height: width, ), ), ), ), Padding( padding: EdgeInsets.only(top: 5), child: InkWell( onTap: () { _sendPicture(); }, child: fixedText( I18n.of(context).upload_avatar, color: Constants.BlackTextColor, ), )), ], ), ); } void _sendPicture() async { if (await CustomUI.showPhotoPermissionSetting(context)) { var tempFile = await ImagePicker.pickImage(source: ImageSource.gallery); if (tempFile != null) { //裁剪图片 _cropPicture(tempFile); } } } String uploadImageUrl; void _cropPicture(tempFile) async { File croppedFile = await ImageCropper.cropImage( sourcePath: tempFile.path, aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1), ); uploadImageUrl = null; if (croppedFile != null) { headFile = croppedFile; Map data = {"type": 1, "userId": UserData().basicInfo.userId}; data['sign'] = TokenMgr().getSign(data); Response response = await HttpUtil() .uploadFile(headFile, data, 'upload/file/postflie', 'image'); var resData = response.data; if (resData['code'] == 0 && resData['msg'] != null) { setState(() { uploadImageUrl = resData['msg']; }); } else { showToast(I18n.of(context).fail); } setState(() {}); } else { print('裁剪失败---'); } } //是否隐藏社交账号 Widget _buildHiddenButtom() { Widget left = Text( I18n.of(context).hide_account1, textScaleFactor: 1.0, style: TextStyle(fontSize: LeftTextFontSize, fontWeight: FontWeight.w500), ); Widget right = new Expanded( child: Container( margin: EdgeInsets.only(right: 20), alignment: Alignment.centerRight, child: new Switch( activeTrackColor: Constants.ConfrimButtonColor.withOpacity(0.3), value: isHiddenSocialAccount, onChanged: (bool val) { setState(() { isHiddenSocialAccount = !isHiddenSocialAccount; }); }, ))); return new Container( decoration: _getCardDecoration(), margin: EdgeInsets.only(top: 15, bottom: 0), padding: EdgeInsets.only(left: BorderLeft), height: 53, child: new Row( children: [left, right], ), ); } //更多信息 Widget _buildMoreInfo() { Widget tip = CustomUI.buildTopTip(BorderLeft, I18n.of(context).more_information); //选择升高 void selectHeight() async { Result temp = await CityPickers.showCityPicker( context: context, showType: ShowType.p, provincesData: WebData().heightData, citiesData: WebData().heightListData, height: 280, ); setState(() { if (temp == null) return; heightStr = "${temp.provinceName}"; heightId = temp.provinceId; }); } //选择升高 void selectWeight() async { Result temp = await CityPickers.showCityPicker( context: context, showType: ShowType.p, provincesData: WebData().weightData, citiesData: WebData().weightListData, height: 280, ); setState(() { if (temp == null) return; weightStr = "${temp.provinceName}"; weightId = temp.provinceId; }); } //个人介绍框 var myselfBox = Container( margin: EdgeInsets.only(left: BorderLeft, bottom: 0), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: 90, margin: EdgeInsets.only(top: 14), child: Text( I18n.of(context).self_introduction, textScaleFactor: 1.0, style: LetfTextStyle, )), Expanded( child: TextField( keyboardAppearance: Brightness.light, controller: mymsgController, style: TextStyle( fontSize: 14, color: Constants.BlackTextColor, textBaseline: TextBaseline.alphabetic), decoration: InputDecoration( contentPadding: EdgeInsets.only(top: 14, right: 10, bottom: 10, left: 10), hintText: I18n.of(context).introduce_yourself, hintStyle: TextStyle(fontSize: 14, color: Colors.grey), border: InputBorder.none, ), maxLines: 5, inputFormatters: [LengthLimitingTextInputFormatter(50)], ), ) ], ), ); List basicList = [ _bottomBorderBox(I18n.of(context).height, heightStr, false, null, heightId != '0', selectHeight), _buildDivider(), _bottomBorderBox(I18n.of(context).weight, weightStr, false, null, weightId != '0', selectWeight), _buildDivider(), myselfBox, ]; Widget socialCard = new Container( color: Colors.white, child: new Column( children: basicList, ), ); return new Column( children: [tip, socialCard], ); } }