feat: loadingUtil 封装

This commit is contained in:
louis 2024-03-19 10:02:20 +08:00
parent 916272bf3b
commit 142c8b5f06
6 changed files with 170 additions and 150 deletions

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:sk_base_mobile/util/loading_util.dart';
import 'package:timeago/timeago.dart' as timeago; import 'package:timeago/timeago.dart' as timeago;
import 'package:sk_base_mobile/constants/cache_key.dart'; import 'package:sk_base_mobile/constants/cache_key.dart';
import 'package:sk_base_mobile/services/app_info.service.dart'; import 'package:sk_base_mobile/services/app_info.service.dart';
@ -26,6 +27,9 @@ class Global {
/// ///
timeago.setLocaleMessages('en', timeago.EnMessages()); timeago.setLocaleMessages('en', timeago.EnMessages());
/// Loading工具
await Get.putAsync<LoadingUtil>(() => LoadingUtil().init());
/// ///
await Get.putAsync<StorageService>(() => StorageService().init()); await Get.putAsync<StorageService>(() => StorageService().init());

View File

@ -39,113 +39,113 @@ class _MinePageState extends State<MinePage>
Widget _buildBody() { Widget _buildBody() {
return Column(children: [ return Column(children: [
Container( // Container(
height: ScreenAdaper.height(360), // height: ScreenAdaper.height(360),
width: ScreenAdaper.screenWidth(), // width: ScreenAdaper.screenWidth(),
decoration: const BoxDecoration( // decoration: const BoxDecoration(
image: DecorationImage( // image: DecorationImage(
fit: BoxFit.cover, // fit: BoxFit.cover,
image: AssetImage('assets/images/mine_bg.png'))), // image: AssetImage('assets/images/mine_bg.png'))),
child: Padding( // child: Padding(
padding: EdgeInsets.symmetric( // padding: EdgeInsets.symmetric(
horizontal: ScreenAdaper.width(20), // horizontal: ScreenAdaper.width(20),
vertical: ScreenAdaper.height(20)), // vertical: ScreenAdaper.height(20)),
child: Column(children: [ // child: Column(children: [
SizedBox( // SizedBox(
height: ScreenAdaper.height(30), // height: ScreenAdaper.height(30),
), // ),
Row( // Row(
children: [ // children: [
const Spacer(), // const Spacer(),
Container( // Container(
height: ScreenAdaper.width(40), // height: ScreenAdaper.width(40),
width: ScreenAdaper.width(40), // width: ScreenAdaper.width(40),
padding: EdgeInsets.all(ScreenAdaper.width(2)), // padding: EdgeInsets.all(ScreenAdaper.width(2)),
decoration: BoxDecoration( // decoration: BoxDecoration(
borderRadius: BorderRadius.circular(ScreenAdaper.sp(40)), // borderRadius: BorderRadius.circular(ScreenAdaper.sp(40)),
color: const Color(0xFF000000).withOpacity(0.3)), // color: const Color(0xFF000000).withOpacity(0.3)),
child: const SizedBox(), // child: const SizedBox(),
) // )
], // ],
), // ),
SizedBox( // SizedBox(
height: ScreenAdaper.height(120), // height: ScreenAdaper.height(120),
), // ),
Row( // Row(
children: [ // children: [
Expanded( // Expanded(
child: Column( // child: Column(
crossAxisAlignment: CrossAxisAlignment.start, // crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center, // mainAxisAlignment: MainAxisAlignment.center,
children: [ // children: [
Row( // Row(
crossAxisAlignment: CrossAxisAlignment.center, // crossAxisAlignment: CrossAxisAlignment.center,
children: [ // children: [
Obx(() => Text( // Obx(() => Text(
AuthStore.to.userInfo.value.nickname ?? '', // AuthStore.to.userInfo.value.nickname ?? '',
style: TextStyle( // style: TextStyle(
fontSize: ScreenAdaper.sp(20), // fontSize: ScreenAdaper.sp(20),
fontWeight: FontWeight.w400), // fontWeight: FontWeight.w400),
)), // )),
SizedBox( // SizedBox(
width: ScreenAdaper.width(3), // width: ScreenAdaper.width(3),
), // ),
InkWell( // InkWell(
onTap: () { // onTap: () {
Get.toNamed(RouteConfig.userinfo); // Get.toNamed(RouteConfig.userinfo);
}, // },
child: Image( // child: Image(
image: // image:
const AssetImage('assets/images/edit_icon.png'), // const AssetImage('assets/images/edit_icon.png'),
height: ScreenAdaper.width(20), // height: ScreenAdaper.width(20),
), // ),
) // )
], // ],
), // ),
SizedBox( // SizedBox(
height: ScreenAdaper.height(15), // height: ScreenAdaper.height(15),
), // ),
Text(StorageService.to.getString(CacheKeys.deviceUUID) ?? // Text(StorageService.to.getString(CacheKeys.deviceUUID) ??
''), // ''),
Row( // Row(
children: [ // children: [
SizedBox( // SizedBox(
width: ScreenAdaper.width(210), // width: ScreenAdaper.width(210),
child: Text( // child: Text(
'ID: ${AuthStore.to.userInfo.value.id}', // 'ID: ${AuthStore.to.userInfo.value.id}',
overflow: TextOverflow.ellipsis, // overflow: TextOverflow.ellipsis,
maxLines: 2, // maxLines: 2,
style: TextStyle( // style: TextStyle(
fontSize: ScreenAdaper.sp(16), // fontSize: ScreenAdaper.sp(16),
color: Colors.grey[500]), // color: Colors.grey[500]),
), // ),
), // ),
InkWell( // InkWell(
onTap: () {}, // onTap: () {},
child: Container( // child: Container(
alignment: Alignment.topCenter, // alignment: Alignment.topCenter,
width: ScreenAdaper.width(50), // width: ScreenAdaper.width(50),
height: ScreenAdaper.height(30), // height: ScreenAdaper.height(30),
padding: EdgeInsets.symmetric( // padding: EdgeInsets.symmetric(
horizontal: ScreenAdaper.width(5)), // horizontal: ScreenAdaper.width(5)),
decoration: BoxDecoration( // decoration: BoxDecoration(
color: const Color(0xFF454545), // color: const Color(0xFF454545),
borderRadius: BorderRadius.circular(5)), // borderRadius: BorderRadius.circular(5)),
child: Text('copy', // child: Text('copy',
style: TextStyle( // style: TextStyle(
color: AppTheme.white, // color: AppTheme.white,
fontSize: ScreenAdaper.sp(16)))), // fontSize: ScreenAdaper.sp(16)))),
) // )
], // ],
) // )
], // ],
)), // )),
MyAvatarWidget() // MyAvatarWidget()
], // ],
) // )
]), // ]),
), // ),
), // ),
Expanded(child: MineSettingsPage()) Expanded(child: MineSettingsPage())
// Expanded( // Expanded(
// child: DefaultTabController( // child: DefaultTabController(

View File

@ -47,7 +47,7 @@ class AuthStore extends GetxController {
} }
Future<void> deleteAccount() async { Future<void> deleteAccount() async {
await LoadingUtil.show(status: 'Deleting...'); await LoadingUtil.to.show(status: 'Deleting...');
try { try {
final response = await Api.deleteAccount(); final response = await Api.deleteAccount();
if (response.data != null) { if (response.data != null) {
@ -57,24 +57,25 @@ class AuthStore extends GetxController {
} catch (e) { } catch (e) {
await SnackBarUtil().error('Delete account faield. Please try again.'); await SnackBarUtil().error('Delete account faield. Please try again.');
} finally { } finally {
await LoadingUtil.dismiss(); await LoadingUtil.to.dismiss();
; ;
} }
} }
Future<void> logout({bool force = false}) async { Future<void> logout({bool force = false}) async {
LoadingUtil.show(status: 'Logout...'); LoadingUtil.to.show(status: 'Logout...');
await StorageService.to.remove(CacheKeys.token, isWithUser: false); await StorageService.to.remove(CacheKeys.token, isWithUser: false);
await StorageService.to.remove(CacheKeys.userInfo, isWithUser: false); await StorageService.to.remove(CacheKeys.userInfo, isWithUser: false);
try { try {
// final response = await Api.logout(); // final response = await Api.logout();
// if (response.data != null) { // if (response.data != null) {
LoggerUtil().info('[Store-Auth] Logout succeed.'); LoggerUtil().info('[Store-Auth] Logout succeed.');
if (Get.context != null) Get.offAllNamed(RouteConfig.login); Get.offAllNamed(RouteConfig.login);
// } // }
} catch (e) { } catch (e) {
print(e);
} finally { } finally {
LoadingUtil.dismiss(); LoadingUtil.to.dismiss();
} }
} }
@ -88,7 +89,7 @@ class AuthStore extends GetxController {
// return; // return;
// } // }
LoadingUtil.show(status: 'Login...'); LoadingUtil.to.show();
TapToDismissKeyboard.dismissOf(context: Get.context!); TapToDismissKeyboard.dismissOf(context: Get.context!);
try { try {
await Future.delayed(const Duration(seconds: 1)); await Future.delayed(const Duration(seconds: 1));
@ -107,7 +108,7 @@ class AuthStore extends GetxController {
} catch (e) { } catch (e) {
await SnackBarUtil().error('账号密码错误'); await SnackBarUtil().error('账号密码错误');
} finally { } finally {
LoadingUtil.dismiss(); LoadingUtil.to.dismiss();
} }
} }
@ -118,7 +119,7 @@ class AuthStore extends GetxController {
} }
Future<void> getUserInfo() async { Future<void> getUserInfo() async {
await LoadingUtil.show(status: 'Loading...'); await LoadingUtil.to.show();
try { try {
final response = await Api.getUserInfo(); final response = await Api.getUserInfo();
if (response.data != null) { if (response.data != null) {
@ -128,12 +129,12 @@ class AuthStore extends GetxController {
} catch (e) { } catch (e) {
SnackBarUtil().error('$e'); SnackBarUtil().error('$e');
} finally { } finally {
LoadingUtil.dismiss(); LoadingUtil.to.dismiss();
} }
} }
Future<void> saveUserInfo(Map<String, dynamic> data) async { Future<void> saveUserInfo(Map<String, dynamic> data) async {
LoadingUtil.show(status: 'Saving...'); LoadingUtil.to.show(status: 'Saving...');
try { try {
final res = await Api.saveUserInfo(data); final res = await Api.saveUserInfo(data);
if (res.data != null) { if (res.data != null) {
@ -143,7 +144,7 @@ class AuthStore extends GetxController {
} catch (e) { } catch (e) {
SnackBarUtil().error('$e'); SnackBarUtil().error('$e');
} finally { } finally {
LoadingUtil.dismiss(); LoadingUtil.to.dismiss();
} }
} }

View File

@ -4,46 +4,61 @@ import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:sk_base_mobile/app_theme.dart'; import 'package:sk_base_mobile/app_theme.dart';
import 'package:sk_base_mobile/util/screen_adaper_util.dart'; import 'package:sk_base_mobile/util/screen_adaper_util.dart';
class LoadingUtil { class LoadingUtil extends GetxController {
LoadingUtil(); static LoadingUtil get to => Get.find();
static Future<void> show({String? status}) async { OverlayEntry? _loadingOverlay;
return showLoading(status: status ?? 'Loading...');
Future<LoadingUtil> init() async {
return this;
} }
static Future<void> dismiss() async { Future<void> show({String? status}) async {
return showLoading(status: status);
}
Future<void> dismiss() async {
return hideLoading(); return hideLoading();
} }
static showLoading({String? status}) async { showLoading({String? status}) async {
await showDialog( hideLoading();
context: Get.context!,
barrierColor: AppTheme.barrierColor, _loadingOverlay = OverlayEntry(
barrierDismissible: false,
builder: (BuildContext context) { builder: (BuildContext context) {
return WillPopScope( return WillPopScope(
onWillPop: () async => false, onWillPop: () async => false,
child: GestureDetector( child: Stack(
child: Container( children: <Widget>[
color: Colors.black54, ModalBarrier(dismissible: false, color: AppTheme.barrierColor),
child: Center( Center(
child: LoadingAnimationWidget.fourRotatingDots( child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
LoadingAnimationWidget.fourRotatingDots(
color: AppTheme.primaryColor, color: AppTheme.primaryColor,
size: ScreenAdaper.sp(50), size: ScreenAdaper.sp(50),
), ),
if (status != null)
SizedBox(width: ScreenAdaper.width(20)),
if (status != null)
Text(status,
style: TextStyle(
color: AppTheme.primaryColor,
fontSize: ScreenAdaper.sp(20)))
],
), ),
), )
onTap: () { ],
// 退 ));
// Navigator.of(context).pop();
},
),
);
}, },
); );
Overlay.of(Get.overlayContext!).insert(_loadingOverlay!);
} }
static hideLoading() { hideLoading() {
Navigator.of(Get.context!).pop(); _loadingOverlay?.remove();
_loadingOverlay = null;
} }
} }

View File

@ -81,7 +81,7 @@ class MyAvatarController extends GetxController {
final uploadImgFilePath = ''.obs; final uploadImgFilePath = ''.obs;
Future<void> photoPicker() async { Future<void> photoPicker() async {
await PhotoPickerUtil().showPicker(callback: (XFile pickedFile) async { await PhotoPickerUtil().showPicker(callback: (XFile pickedFile) async {
await LoadingUtil.show(status: 'Uploading...'); await LoadingUtil.to.show(status: 'Uploading...');
try { try {
String? filename = await MediaUtil().uploadImg(File(pickedFile.path)); String? filename = await MediaUtil().uploadImg(File(pickedFile.path));
if (filename.isNotEmpty) { if (filename.isNotEmpty) {
@ -95,7 +95,7 @@ class MyAvatarController extends GetxController {
} catch (e) { } catch (e) {
SnackBarUtil().error('Update avatar failed.'); SnackBarUtil().error('Update avatar failed.');
} finally { } finally {
await LoadingUtil.dismiss(); await LoadingUtil.to.dismiss();
} }
}); });
} }