From bc0550ae13b26fb1bc0dbacd80556b33112e53ce Mon Sep 17 00:00:00 2001 From: Key Date: Wed, 12 Jul 2023 21:19:39 +0800 Subject: [PATCH] fixed: avatar修改 --- lib/common/extension/exception_ext.dart | 2 ++ lib/pages/user/bloc/user_bloc.dart | 46 ++++++++++++++++++---------------------------- lib/pages/user/modify/modify_user_avatar_page.dart | 175 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------ lib/pages/user/modify/user_avatar_bloc/user_avatar_bloc.dart | 20 +++++++++++--------- lib/utils/aliyun_oss_util.dart | 37 +++++++++++++++++++++++-------------- 5 files changed, 127 insertions(+), 153 deletions(-) diff --git a/lib/common/extension/exception_ext.dart b/lib/common/extension/exception_ext.dart index a2e9b3a..59a4480 100644 --- a/lib/common/extension/exception_ext.dart +++ b/lib/common/extension/exception_ext.dart @@ -4,6 +4,8 @@ extension ExceptionExtension on Exception { String get getShowMessage { if (this is ApiException) { return (this as ApiException).message ?? '未知错误'; + } else if (this is FormatException) { + return (this as FormatException).message; } else { return '未知错误'; } diff --git a/lib/pages/user/bloc/user_bloc.dart b/lib/pages/user/bloc/user_bloc.dart index d83e3b5..8e0d3b0 100644 --- a/lib/pages/user/bloc/user_bloc.dart +++ b/lib/pages/user/bloc/user_bloc.dart @@ -35,32 +35,24 @@ class UserBloc extends Bloc { void _updateUser(UserUpdate event, Emitter emitter) async { Log.d('_updateUser, event: ${event.type}, emitter.isDone: ${emitter.isDone}, text=${event.content}'); UserEntity user = UserUtil.getUser()!; - switch (event.type) { - case ModifyUserInformationType.avatar: - String avatarUrl = event.content; - try { + try { + switch (event.type) { + case ModifyUserInformationType.avatar: + String avatarUrl = event.content; await UserDao.updateUserInfoField(avatarUrl: avatarUrl); // 修改成功,更新本地缓存及UI user.avatarUrl = avatarUrl; emitter(UserInfoUpdated()); - } catch (e) { - Log.e('_updateUser avatarUrl, e: $e'); - } - break; - case ModifyUserInformationType.name: - String name = event.content; - try { + break; + case ModifyUserInformationType.name: + String name = event.content; await UserDao.updateUserInfoField(name: name); // 修改成功,更新本地缓存及UI user.name = name; emitter(UserInfoUpdated()); - } catch (e) { - Log.e('_updateUser name, e: $e'); - } - break; - case ModifyUserInformationType.age: - // todo 校验格式 - try { + break; + case ModifyUserInformationType.age: + // todo 校验格式 int age; try { age = int.parse(event.content); @@ -72,20 +64,18 @@ class UserBloc extends Bloc { // 修改成功,更新本地缓存及UI user.age = age; emitter(UserInfoUpdated()); - } catch (e) { - Log.e('_updateUser age, e: $e'); - } - break; - case ModifyUserInformationType.gender: - try { + break; + case ModifyUserInformationType.gender: var gender = int.parse(event.content); await UserDao.updateUserInfoField(gender: gender); user.gender = gender; emitter(UserInfoUpdated()); - } catch (e) { - Log.e('_updateUser gender, e: $e'); - } - break; + break; + } + // 服务器保存成功后本地再保存一下 + UserUtil.saveUser(user); + } catch (e) { + Log.e('修改个人信息失败: $e'); } } } diff --git a/lib/pages/user/modify/modify_user_avatar_page.dart b/lib/pages/user/modify/modify_user_avatar_page.dart index 3c405ed..b697a12 100644 --- a/lib/pages/user/modify/modify_user_avatar_page.dart +++ b/lib/pages/user/modify/modify_user_avatar_page.dart @@ -30,39 +30,39 @@ class ModifyUserAvatarPage extends StatelessWidget { class _ModifyUserAvatarPage extends StatelessWidget { const _ModifyUserAvatarPage({required this.pageType}); + final int pageType; @override Widget build(BuildContext context) { return MultiBlocListener( listeners: [ - BlocListener( - listener: (context, state){ - if (state is UserInfoUpdated) { - if (pageType == 1) { - showToast('修改成功'); - popPage(); - } else { - context.read().add(ChangeUserEnterAppStateEvent()); - } - } - }), - BlocListener( - listener: (context,state){ + BlocListener(listener: (context, state) { + if (state is UserInfoUpdated) { + if (pageType == 1) { + showToast('修改成功'); + popPage(); + } else { + context.read().add(ChangeUserEnterAppStateEvent()); + } + } + }), + BlocListener( + listener: (context, state) { if (state is ChangeImageState) { - context.read().add(UserUpdate(ModifyUserInformationType.avatar,state.imageUrl)); + context.read().add(UserUpdate(ModifyUserInformationType.avatar, state.imageUrl)); } - },) + }, + ) ], - child: pageType == 0 ? _setUserAvatarView():_modifyUserAvatarPageView(), + child: pageType == 0 ? _setUserAvatarView() : _modifyUserAvatarPageView(), ); } ///个人信息修改头像 - Widget _modifyUserAvatarPageView() => BlocBuilder( - builder: (context,state){ + Widget _modifyUserAvatarPageView() => BlocBuilder(builder: (context, state) { return Scaffold( - appBar:const WEAppBar( + appBar: const WEAppBar( titleText: '头像修改', ), body: SafeArea( @@ -77,64 +77,53 @@ class _ModifyUserAvatarPage extends StatelessWidget { }); ///新用户设置头像 - Widget _setUserAvatarView() => BlocBuilder( - builder: (context, state) { - final bloc = BlocProvider.of(context); - return Container( - color: Colors.white, - child: SafeArea( - child: Column( - children: [ - 20.verticalSpace, - Row( - children: [ - Image.asset( - 'wow_logo'.assetPng, - height: 49.h, - width: 84.w, - ), - Text( - '欢迎登录wow english\n接下来请填写一下您的个人信息吧', - textAlign: TextAlign.left, - style: TextStyle( - fontSize: 17.sp, - color: const Color(0xFF666666) + Widget _setUserAvatarView() => BlocBuilder(builder: (context, state) { + final bloc = BlocProvider.of(context); + return Container( + color: Colors.white, + child: SafeArea( + child: Column( + children: [ + 20.verticalSpace, + Row( + children: [ + Image.asset( + 'wow_logo'.assetPng, + height: 49.h, + width: 84.w, ), - ) - ], - ), - 15.verticalSpace, - _avatarImageWidget(), - 10.verticalSpace, - Container( - width: 176.w, - height: 52.h, - padding: const EdgeInsets.all(5), - decoration: BoxDecoration( - image: DecorationImage( - image: AssetImage(bloc.canInsertApp?'oninto'.assetPng:'intowow'.assetPng), - fit: BoxFit.fill + Text( + '欢迎登录wow english\n接下来请填写一下您的个人信息吧', + textAlign: TextAlign.left, + style: TextStyle(fontSize: 17.sp, color: const Color(0xFF666666)), ) + ], ), - alignment: Alignment.center, - child: Text( - '进入wow english', - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 12.sp, - color: Colors.white + 15.verticalSpace, + _avatarImageWidget(), + 10.verticalSpace, + Container( + width: 176.w, + height: 52.h, + padding: const EdgeInsets.all(5), + decoration: BoxDecoration( + image: DecorationImage( + image: AssetImage(bloc.canInsertApp ? 'oninto'.assetPng : 'intowow'.assetPng), + fit: BoxFit.fill)), + alignment: Alignment.center, + child: Text( + '进入wow english', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12.sp, color: Colors.white), ), - ), - ) - ], + ) + ], + ), ), - ), - ); - } - ); + ); + }); - Widget _avatarImageWidget() => BlocBuilder( - builder: (context, state){ + Widget _avatarImageWidget() => BlocBuilder(builder: (context, state) { final bloc = BlocProvider.of(context); return Row( mainAxisAlignment: MainAxisAlignment.center, @@ -144,17 +133,13 @@ class _ModifyUserAvatarPage extends StatelessWidget { height: 197.h, padding: const EdgeInsets.all(5), decoration: BoxDecoration( - image: DecorationImage( - image: AssetImage('video_background'.assetPng), - fit: BoxFit.fill - ) - ), - child: bloc.file == null ? - OwImageWidget(name: bloc.imageUrl): - Image.file( - File(bloc.file!.path), - fit: BoxFit.fill, - ), + image: DecorationImage(image: AssetImage('video_background'.assetPng), fit: BoxFit.fill)), + child: bloc.file == null + ? OwImageWidget(name: bloc.imageUrl) + : Image.file( + File(bloc.file!.path), + fit: BoxFit.fill, + ), ), 54.horizontalSpace, Column( @@ -166,19 +151,12 @@ class _ModifyUserAvatarPage extends StatelessWidget { width: 222.w, height: 65.h, alignment: Alignment.center, - decoration: BoxDecoration( - image: DecorationImage( - image: AssetImage('alter'.assetPng), - fit: BoxFit.fill - ) - ), + decoration: + BoxDecoration(image: DecorationImage(image: AssetImage('alter'.assetPng), fit: BoxFit.fill)), child: Text( '拍照修改头像', textAlign: TextAlign.center, - style: TextStyle( - color: Colors.white, - fontSize: 20.sp - ), + style: TextStyle(color: Colors.white, fontSize: 20.sp), ), ), ), @@ -189,19 +167,12 @@ class _ModifyUserAvatarPage extends StatelessWidget { width: 222.w, height: 65.h, alignment: Alignment.center, - decoration: BoxDecoration( - image: DecorationImage( - image: AssetImage('alter'.assetPng), - fit: BoxFit.fill - ) - ), + decoration: + BoxDecoration(image: DecorationImage(image: AssetImage('alter'.assetPng), fit: BoxFit.fill)), child: Text( '从相册选择', textAlign: TextAlign.center, - style: TextStyle( - color: Colors.white, - fontSize: 20.sp - ), + style: TextStyle(color: Colors.white, fontSize: 20.sp), ), ), ) diff --git a/lib/pages/user/modify/user_avatar_bloc/user_avatar_bloc.dart b/lib/pages/user/modify/user_avatar_bloc/user_avatar_bloc.dart index 2522882..625cfd4 100644 --- a/lib/pages/user/modify/user_avatar_bloc/user_avatar_bloc.dart +++ b/lib/pages/user/modify/user_avatar_bloc/user_avatar_bloc.dart @@ -12,6 +12,7 @@ import 'package:wow_english/common/dialogs/show_dialog.dart'; import 'package:wow_english/route/route.dart'; import 'package:wow_english/utils/aliyun_oss_util.dart'; import 'package:wow_english/utils/log_util.dart'; +import 'package:wow_english/utils/toast_util.dart'; part 'user_avatar_event.dart'; part 'user_avatar_state.dart'; @@ -38,10 +39,8 @@ class UserAvatarBloc extends Bloc { } Future _uploadAvatar(String imagePath) async { - // todo 加个loading UI - EasyLoading.showToast(''); String avatarUrl = await AliyunOssUtil.uploadFile(imagePath); - EasyLoading.dismiss(); + debugPrint('>>>>>>>>>>阿里云图片地址: $avatarUrl'); return avatarUrl; } @@ -51,7 +50,7 @@ class UserAvatarBloc extends Bloc { final androidInfo = await DeviceInfoPlugin().androidInfo; if (androidInfo.version.sdkInt <= 32) { permission = Permission.storage; - } else { + } else { permission = Permission.photos; } } else { @@ -63,12 +62,15 @@ class UserAvatarBloc extends Bloc { return; } _file = await picker.pickImage(source: ImageSource.gallery); + EasyLoading.show(); try { final urlStr = await _uploadAvatar(_file!.path); emitter(ChangeImageState(urlStr)); } catch (e) { Log.e('上传头像失败:$e'); + showToast('上传头像失败: $e'); } + EasyLoading.dismiss(); }); } @@ -79,17 +81,19 @@ class UserAvatarBloc extends Bloc { return; } _file = await picker.pickImage(source: ImageSource.camera); + EasyLoading.show(); try { final urlStr = await _uploadAvatar(_file!.path); emitter(ChangeImageState(urlStr)); } catch (e) { Log.e('上传头像失败:$e'); + showToast('上传头像失败: $e'); } - //emitter(ChangeImageState()); + EasyLoading.dismiss(); }); } - void _changeUserEnterAppState(ChangeUserEnterAppStateEvent event,Emitter emitter) async { + void _changeUserEnterAppState(ChangeUserEnterAppStateEvent event, Emitter emitter) async { _canInsertApp = true; emitter(ChangeUserEnterAppState()); } @@ -104,9 +108,7 @@ class UserAvatarBloc extends Bloc { showDialog(permission); } else if (status.isRestricted) { _requestPermission(permission); - } else { - - } + } else {} return false; } diff --git a/lib/utils/aliyun_oss_util.dart b/lib/utils/aliyun_oss_util.dart index 727b394..184d478 100644 --- a/lib/utils/aliyun_oss_util.dart +++ b/lib/utils/aliyun_oss_util.dart @@ -1,6 +1,6 @@ import 'package:dio/dio.dart'; -import 'package:flutter/cupertino.dart'; import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart'; +import 'package:wow_english/common/request/api_response/api_response_entity.dart'; import 'package:wow_english/common/request/request_client.dart'; import 'package:wow_english/models/aliyun_oss_upload_sts_entity.dart'; import 'package:wow_english/utils/log_util.dart'; @@ -10,15 +10,16 @@ import 'package:wow_english/utils/log_util.dart'; class AliyunOssUtil { static Future uploadFile(String filePath) async { // 取出文件名 - String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length); - Log.d("待上传文件fileName: $fileName"); + //String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length); + String fileName = filePath.split('/').last; + Log.d("待上传文件: [$filePath], 截取的fileName: [$fileName]"); // 获取鉴权信息 AliyunOssUploadStsEntity? stsEntity = await _getSts(fileName); - if(stsEntity == null) { - // todo 为空的情况抛出错误 - return ''; + if (stsEntity == null) { + // 为空的情况抛出错误 + throw 'STS为空'; } - debugPrint('鉴权信息$stsEntity'); + //Log.d('鉴权信息: $stsEntity'); // 鉴权 Client.init( ossEndpoint: stsEntity.endpoint, @@ -27,17 +28,17 @@ class AliyunOssUtil { ); // 上传文件 - await Client().putObjectFile( + final Response resp = await Client().putObjectFile( filePath, fileKey: stsEntity.fileKey, option: PutRequestOption( onSendProgress: (count, total) { - Log.d("send: count = $count, and total = $total"); + Log.d("send: $count/$total"); }, onReceiveProgress: (count, total) { - Log.d("receive: count = $count, and total = $total"); + Log.d("receive: $count/$total"); }, - aclModel: AclMode.publicRead, + aclModel: AclMode.inherited, callback: Callback( callbackUrl: stsEntity.callbackParam.callbackUrl, callbackBody: stsEntity.callbackParam.callbackBody, @@ -45,13 +46,21 @@ class AliyunOssUtil { ), ), ); - return '${stsEntity.host}/${stsEntity.fileKey}'; + var url = '${stsEntity.host}/${stsEntity.fileKey}'; + // 正确返回时,是我们自己服务器的回调,所以使用我们的格式解析 + var result = ApiResponse.fromJson(resp.data); + Log.d('上传结果: $result, url: $url'); + if (result.code != 200) { + // 上传失败抛出错误 + throw result.msg ?? '未知错误'; + } + return url; } /// 获取鉴权信息 static Future _getSts(String fileName) async { - var result = await requestClient.get(Apis.aliyunOssSts, queryParameters: {'fileName': fileName}); - debugPrint('鉴权结果$result'); + var result = + await requestClient.get(Apis.aliyunOssSts, queryParameters: {'fileName': fileName}); return result; } } -- libgit2 0.22.2