From f79e83848ad638a7f7f616cadb2b0fa73552373b Mon Sep 17 00:00:00 2001 From: fff Date: Wed, 15 Jan 2025 14:17:24 +0800 Subject: [PATCH] =?UTF-8?q?UI=E4=BF=AE=E6=94=B90115=EF=BC=9A1415?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/address/address_map_page.dart | 162 +-- lib/address/edit_address_page.dart | 14 +- lib/base_state.dart | 16 +- lib/community/community_child_list.dart | 7 + lib/community/community_child_page.dart | 100 +- lib/community/community_course.dart | 43 +- lib/community/community_details.dart | 51 +- lib/community/community_list.dart | 12 +- .../community_view/class_details.dart | 33 +- .../community_view/community_dynamic.dart | 364 ++--- .../community_view/course_banner.dart | 39 +- lib/community/community_view/home_class.dart | 1 - .../headlines/activity_top_list.dart | 4 - lib/community/headlines/article_list.dart | 32 +- lib/community/headlines/article_page.dart | 14 +- lib/community/headlines/headlines_banner.dart | 38 +- .../headlines/headlines_collection.dart | 2 +- .../headlines/headlines_column_details.dart | 88 +- lib/community/new_community_details.dart | 38 +- lib/community/order_page.dart | 1 + lib/community/photo_view_gallery_screen.dart | 7 +- lib/community/release_dynamic.dart | 27 +- lib/community/report/report_notice.dart | 6 +- lib/community/report/report_page.dart | 290 ++-- lib/community/report/report_success.dart | 2 +- lib/community/share_trends.dart | 207 +-- lib/constant.dart | 16 +- lib/data/article.dart | 2 +- lib/data/article.g.dart | 6 +- lib/data/vip_card.dart | 32 + lib/home/activity_list_page.dart | 9 +- lib/home/founder_story_page.dart | 316 +---- lib/home/guide_page.dart | 55 +- lib/home/help_farmers/help_farmers_page.dart | 63 +- lib/home/home_page.dart | 108 +- lib/home/home_view/activity_list.dart | 6 +- lib/home/home_view/brand_view.dart | 2 +- lib/home/home_view/coupon.dart | 27 +- lib/home/home_view/discount_zone.dart | 1 - lib/home/home_view/featured_acticvity.dart | 49 +- lib/home/home_view/founder_store.dart | 7 +- lib/home/home_view/happy_help_farmers.dart | 2 - lib/home/home_view/home_banner.dart | 33 +- lib/home/home_view/home_integral_store.dart | 10 +- lib/home/home_view/home_recommend_goods.dart | 8 + lib/home/home_view/hot_article.dart | 11 +- lib/home/home_view/quick_order.dart | 96 +- lib/home/home_view/shortcut_operation.dart | 1 - lib/home/home_view/sign_view.dart | 31 +- lib/home/home_view/top_selling_list.dart | 3 + lib/home/home_view/union_entry.dart | 1 - lib/home/home_view/welfare_core.dart | 1 - lib/home/huixiang_brand_page.dart | 16 +- lib/home/huixiang_view/huixiang_banner.dart | 36 +- lib/home/huixiang_view/origin_info.dart | 1 + lib/home/points_mall_page.dart | 23 +- .../points_mall_view/point_mall_user.dart | 14 +- .../points_mall_view/points_goods_title.dart | 5 +- .../points_mall_view/points_goods_view.dart | 3 +- .../points_mall_view/points_mall_banner.dart | 33 +- lib/home/trading_card_page.dart | 8 +- lib/home/welfare_exchange.dart | 36 +- lib/home/welfare_page.dart | 72 +- lib/im/SocketClient.dart | 9 +- lib/im/add_friend.dart | 1 - lib/im/chat_details_page.dart | 534 ++++--- lib/im/chat_friend_group.dart | 18 +- lib/im/chat_setting.dart | 12 +- lib/im/contact_share.dart | 277 ++-- lib/im/database/hx_database.dart | 4 +- lib/im/database/message.dart | 4 +- lib/im/im_search.dart | 143 +- lib/im/im_view/friend_groip_list.dart | 35 +- lib/im/im_view/im_page.dart | 377 ++--- lib/im/im_view/on_chat_msg_instance.dart | 36 +- lib/integral/integral_detailed_page.dart | 131 +- lib/integral/integral_page.dart | 50 +- lib/integral/intergra_view/integral_vip.dart | 51 +- .../integral_store_details_page.dart | 66 +- lib/login/captcha/block_puzzle_captcha.dart | 4 +- lib/login/login_page.dart | 119 +- lib/login/new_login_page.dart | 80 +- lib/main.dart | 160 +-- lib/main_page.dart | 100 +- lib/message/main_message_page.dart | 8 +- lib/message/real_time_info_page.dart | 14 +- lib/message/system_details.dart | 27 +- lib/message/system_message.dart | 439 +++--- lib/message/system_notice.dart | 26 +- lib/mine/coupon_page.dart | 10 +- lib/mine/coupons_page.dart | 7 +- lib/mine/fans_page.dart | 20 +- lib/mine/follow_page.dart | 14 +- lib/mine/invitation_record.dart | 27 +- lib/mine/manage_address_page.dart | 10 +- lib/mine/mine_card_invalid_page.dart | 10 +- lib/mine/mine_greenery.dart | 14 +- lib/mine/mine_page.dart | 57 +- lib/mine/mine_shop_details.dart | 396 +++--- lib/mine/mine_shop_page.dart | 68 +- lib/mine/mine_shop_recharge.dart | 718 +++------- lib/mine/mine_view/community_follow.dart | 5 +- lib/mine/mine_view/mine_item.dart | 54 +- lib/mine/mine_view/mine_navbar.dart | 146 +- lib/mine/mine_view/mine_order.dart | 23 +- lib/mine/mine_view/mine_view.dart | 33 +- lib/mine/mine_view/wallet_coupon_view.dart | 41 +- lib/mine/mine_vip/binding_assistant_card.dart | 10 +- lib/mine/mine_vip/legal_right_details.dart | 10 +- lib/mine/mine_vip/mine_attainment_page.dart | 8 +- lib/mine/mine_vip/mine_vip_core.dart | 31 +- lib/mine/mine_vip_level_page.dart | 14 +- lib/mine/mine_wallet_page.dart | 108 +- lib/mine/personal_page.dart | 1263 +++++++++++------ lib/mine/recharge_page.dart | 35 +- lib/mine/roll_center_page.dart | 16 +- lib/mine/user_info_page.dart | 44 +- lib/mine/vip_balance_page.dart | 8 +- lib/mine/vip_card_page.dart | 8 +- lib/mine/vip_detail_page.dart | 3 +- lib/mine/vip_pay_code.dart | 12 +- lib/order/bargain_group_order.dart | 23 +- lib/order/exchange_history_page.dart | 373 +++-- lib/order/exchange_order_page.dart | 23 +- lib/order/exchange_order_success_page.dart | 22 +- .../invoices_manage/add_invoices_title.dart | 36 +- .../invoices_manage/edit_invoices_info.dart | 19 +- .../invoices_manage/invoices_detail_page.dart | 32 +- .../invoices_manage/invoices_history.dart | 82 +- .../invoices_manage/invoices_manage_page.dart | 107 +- .../invoices_manage/invoices_title_info.dart | 140 +- lib/order/logistics_information_page.dart | 63 +- lib/order/order_detail_page.dart | 84 +- lib/order/order_history_page.dart | 193 +-- lib/order/order_view/order_address.dart | 15 +- lib/order/order_view/order_commodity.dart | 83 +- lib/order/order_view/order_status.dart | 267 ++-- lib/qr/invite_friends.dart | 76 +- lib/qr/qr_share.dart | 12 +- lib/retrofit/min_api.dart | 3 +- lib/retrofit/min_api.g.dart | 11 +- lib/retrofit/retrofit_api.dart | 5 +- lib/retrofit/retrofit_api.g.dart | 18 +- lib/setting/account_security_page.dart | 57 +- lib/setting/help_feedback_page.dart | 10 +- lib/setting/logout_ing.dart | 46 +- lib/setting/setting_page.dart | 44 +- lib/settlement/settlement.dart | 249 ++-- .../settlement_view/pay_method.dart | 102 +- lib/store/report_assess .dart | 78 +- lib/store/shop/shop_scroll_controller.dart | 215 +++ lib/store/shop/shop_scroll_coordinator.dart | 117 ++ lib/store/shop/shop_scroll_position.dart | 315 ++++ lib/store/shop_details_page.dart | 120 +- .../shopping/activity_prefecture_details.dart | 36 +- .../shopping/shopping_goods_details.dart | 60 +- .../shopping_home/bargain_details.dart | 26 +- .../shopping/shopping_home/group_details.dart | 28 +- .../shopping/shopping_home/search_page.dart | 35 +- .../shopping_home/shopping_home_page.dart | 22 +- lib/store/shopping/shopping_mall_home.dart | 145 +- lib/store/store_order.dart | 420 +++--- lib/store/store_view/product_meals_sku.dart | 31 +- lib/store/store_view/shop_goods.dart | 57 +- lib/store/store_view/store_info.dart | 14 - lib/store/store_view/store_order_list.dart | 114 +- lib/union/union_details_page.dart | 11 +- lib/union/union_list.dart | 68 +- lib/union/union_page.dart | 33 +- lib/utils/app_util.dart | 30 +- lib/utils/shared_preference.dart | 157 ++ lib/utils/upload_async.dart | 5 +- lib/view_widget/hot_item.dart | 105 +- lib/view_widget/icon_text.dart | 73 +- lib/view_widget/login_tips_dialog.dart | 10 +- lib/view_widget/mine_vip_entry.dart | 286 ++-- lib/view_widget/mine_vip_view.dart | 25 +- lib/view_widget/my_appbar.dart | 90 +- lib/view_widget/selector_store_dialog.dart | 119 +- lib/view_widget/update_dialog.dart | 9 +- lib/view_widget/vip_dialog.dart | 65 +- lib/vip/vip_page.dart | 42 +- lib/web/web_page.dart | 34 +- lib/web/web_turntable_activity.dart | 49 +- lib/web/web_view/comment_list.dart | 87 +- lib/web/web_view/input_comment.dart | 27 +- pubspec.lock | 56 + pubspec.yaml | 17 +- 188 files changed, 7016 insertions(+), 7099 deletions(-) create mode 100644 lib/store/shop/shop_scroll_controller.dart create mode 100644 lib/store/shop/shop_scroll_coordinator.dart create mode 100644 lib/store/shop/shop_scroll_position.dart create mode 100644 lib/utils/shared_preference.dart diff --git a/lib/address/address_map_page.dart b/lib/address/address_map_page.dart index 876e6129..1402aa64 100644 --- a/lib/address/address_map_page.dart +++ b/lib/address/address_map_page.dart @@ -9,6 +9,7 @@ import 'package:geolocator/geolocator.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/location.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/request_permission.dart'; import 'package:permission_handler/permission_handler.dart' as PH; import 'package:shared_preferences/shared_preferences.dart'; @@ -46,10 +47,12 @@ class _AddressMapPage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, token: value.getString('token')), - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + LocationInstance.getInstance().startLocation(context, (Position? result) { print("event: $result"); if (result?.latitude != null && result?.longitude != null) { @@ -62,8 +65,7 @@ class _AddressMapPage extends State { heading: 0, speed: 0, speedAccuracy: 0); - LocationInstance.getInstance() - .getAddress(result.latitude, result.longitude) + LocationInstance.getInstance().getAddress(result.latitude, result.longitude) ?.then((value) { if (value != null) { city = value.city ?? ""; @@ -242,158 +244,22 @@ class _AddressMapPage extends State { }, heightRatioWithWidth: 0.82, ); - }); + }, + ); } - // BMFMapController? _mapController; - // BMFCoordinate? bmfCoordinate; - - // void onMapCreated(BMFMapController controller) { - // controller.setMapRegionDidChangeCallback(callback: (status) { - // BMFMapStatus bmfMapStatus = status; - // print("status: ${bmfMapStatus.toMap()}"); - // if (bmfCoordinate?.longitude == status.targetGeoPt?.longitude && - // bmfCoordinate?.latitude == status.targetGeoPt?.latitude) { - // if ((DateTime.now().millisecondsSinceEpoch - time) > 1000) { - // center = status.targetGeoPt; - // searchPoi(center); - // time = DateTime.now().millisecondsSinceEpoch; - // } - // } else { - // bmfCoordinate = status.targetGeoPt; - // } - // }); - // - // setState(() { - // _mapController = controller; - // _mapController?.showUserLocation(true); - // _loadCustomData(); - // addMarker(); - // }); - // } - Position? latLng; - // BMFMarker? bmfMarker; - - // addMarker() { - // bmfMarker?.updateIsLockedToScreen( - // true, - // BMFPoint( - // (Platform.isIOS - // ? MediaQuery.of(context).size.width - // : window.physicalSize.width) / - // 2, - // (Platform.isIOS - // ? MediaQuery.of(context).size.height - // : window.physicalSize.height) / - // 4)); - // } - saveLatLng(Position? latLng) async { - SharedPreferences prefs = await SharedPreferences.getInstance(); - await prefs.setString("latitude", "${latLng?.latitude}"); - await prefs.setString("longitude", "${latLng?.longitude}"); + SharedInstance.instance.saveLatLng(latLng); } - // getLatLng() async { - // SharedPreferences.getInstance().then((value) => { - // setState(() { - // _mapController?.updateMapOptions( - // BMFMapOptions( - // center: BMFCoordinate( - // double.tryParse("${value.getString("latitude")}") ?? 0, - // double.tryParse("${value.getString("longitude")}") ?? 0, - // ), - // zoomLevel: 15, - // showZoomControl: false, - // showMapScaleBar: false, - // rotateEnabled: false, - // ), - // ); - // }) - // }); - // } - // - // BMFMapWidget? map; - // BMFCoordinate? center = BMFCoordinate(30.553111, 114.342366); - @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ searchWidget(), - // Expanded( - // child: Stack( - // children: [ - // Container( - // child: BMFMapWidget( - // mapOptions: BMFMapOptions( - // center: BMFCoordinate(30.553111, 114.342366), - // zoomLevel: 15, - // showZoomControl: false, - // showMapScaleBar: false, - // rotateEnabled: false, - // ), - // onBMFMapCreated: onMapCreated, - // // onCameraMoveEnd: (cameraPosition) { - // // center = cameraPosition.target; - // // searchPoi(center); - // // }, - // // onCameraMove: (cameraPosition) { - // // center = cameraPosition.target; - // // setState(() {}); - // // }, - // // markers: [Marker(position: center)].toSet(), - // // touchPoiEnabled: true, - // // scrollGesturesEnabled: true, - // // customStyleOptions: _customStyleOptions, - // // gestureRecognizers: >[ - // // Factory( - // // () => EagerGestureRecognizer()) - // // ].toSet(), - // ), - // ), - // // Center( - // // child: IgnorePointer( - // // child: Container( - // // margin: EdgeInsets.only(bottom: 44.h), - // // child: Image.asset( - // // "assets/image/icon_address_location.webp", - // // width: 66.w, - // // height: 75.h, - // // ), - // // ), - // // ), - // // ), - // Positioned( - // right: 17, - // bottom: 16, - // child: InkWell( - // onTap: () { - // startLocation(); - // }, - // child: Container( - // width: 32, - // height: 32, - // padding: EdgeInsets.all(8), - // decoration: BoxDecoration( - // borderRadius: BorderRadius.circular(16), - // color: Colors.white, - // ), - // child: Image.asset( - // "assets/image/icon_address_location_action.webp", - // width: 16.w, - // height: 16.h, - // ), - // ), - // ), - // ), - // ], - // ), - // flex: 1, - // ), Expanded( child: Container( child: ListView.separated( @@ -464,14 +330,16 @@ class _AddressMapPage extends State { padding: EdgeInsets.fromLTRB(10, 6, 16, 6), decoration: BoxDecoration( color: Colors.white, - borderRadius: BorderRadius.all(Radius.circular(4)), + borderRadius: BorderRadius.all( + Radius.circular(4), + ), boxShadow: [ BoxShadow( color: Colors.black.withAlpha(12), offset: Offset(0, 3), blurRadius: 14, spreadRadius: 0, - ) + ), ], ), child: Row( diff --git a/lib/address/edit_address_page.dart b/lib/address/edit_address_page.dart index 857512f4..9d994d62 100644 --- a/lib/address/edit_address_page.dart +++ b/lib/address/edit_address_page.dart @@ -5,6 +5,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/address.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -32,11 +33,11 @@ class _EditAddressPage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, token: value.getString('token')), - queryAddress(), - }); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + ); + queryAddress(); } Address? preAddress; @@ -45,8 +46,7 @@ class _EditAddressPage extends State { preAddress = Address.fromJson(widget.arguments); nameController.text = "${preAddress?.username}"; mobileController.text = "${preAddress?.phone}"; - addressController.text = - "${preAddress?.province}${preAddress?.city}${preAddress?.area}"; + addressController.text = "${preAddress?.province}${preAddress?.city}${preAddress?.area}"; houseNumberController.text = "${preAddress?.addressStr}"; setState(() {}); } diff --git a/lib/base_state.dart b/lib/base_state.dart index 02c93619..3b2b387f 100644 --- a/lib/base_state.dart +++ b/lib/base_state.dart @@ -1,7 +1,9 @@ import 'dart:convert'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:huixiang/utils/bridge.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; abstract class BaseState extends State @@ -41,16 +43,16 @@ abstract class BaseState extends State pushRoute() async { String startIntent = await Bridge.getStartIntent(); - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); + print("intent:$startIntent"); String pushData = ""; - if (startIntent != null && startIntent != "") { + if (startIntent.isNotEmpty) { pushData = startIntent; } else { - pushData = sharedPreferences.getString("pushData") ?? ""; + pushData = SharedInstance.instance.pushData; } - if (pushData == null || pushData == "") return; - Map pushMap = jsonDecode(pushData); + if (pushData.isEmpty) return; + Map? pushMap = jsonDecode(pushData); if (pushMap != null) { String routeName = ""; Map params = {}; @@ -108,8 +110,8 @@ abstract class BaseState extends State params["id"] = pushMap["info"]; break; } - sharedPreferences.setString("pushData", ""); - print("xgPushClickAction: routeName: $routeName"); + SharedInstance.instance.savePushData(); + debugPrint("xgPushClickAction: routeName: $routeName"); if (routeName != "") { Navigator.of(context).pushNamed(routeName, arguments: params); } diff --git a/lib/community/community_child_list.dart b/lib/community/community_child_list.dart index 37d7d4df..1b61e77c 100644 --- a/lib/community/community_child_list.dart +++ b/lib/community/community_child_list.dart @@ -1,8 +1,10 @@ +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/comunity_comment.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -33,6 +35,11 @@ class _CommunityChildList extends State { @override void initState() { super.initState(); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); _onRefresh(); } diff --git a/lib/community/community_child_page.dart b/lib/community/community_child_page.dart index 53db887a..343c61d3 100644 --- a/lib/community/community_child_page.dart +++ b/lib/community/community_child_page.dart @@ -9,6 +9,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/comunity_comment.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; @@ -65,7 +66,7 @@ class CommunityChildPageState extends State } ///动态列表 - queryCommunity(String? searchKey) async { + Future queryCommunity({String? searchKey}) async { if (!isRefresh) { isRefresh = true; return; @@ -74,14 +75,12 @@ class CommunityChildPageState extends State return; } isLoadingData = true; - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - userId = value.getString('userId'); - apiService = ApiService(Dio(), - context: context, - token: value.getString("token"), - showLoading: false); - } + userId = SharedInstance.instance.userId; + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false, + ); if (isLoadMore) { pageNum += 1; isLoadMore = false; @@ -103,25 +102,52 @@ class CommunityChildPageState extends State }); refreshController.refreshCompleted(); if (baseData?.isSuccess ?? false) { - if (baseData?.data?.list?.isNotEmpty ?? false) - articles.forEach((element) { - if (element.id == searchKey) { - element.content = jsonEncode(baseData?.data?.list?[0].subjectInfo); - element.mainTitle = baseData?.data?.list?[0].subject; - element.followed = baseData?.data?.list?[0].selfFollow; - element.liked = baseData?.data?.list?[0].selfLike; - element.authorHeadImg = baseData?.data?.list?[0].memberInfo?.avatar; - element.authorName = baseData?.data?.list?[0].memberInfo?.nickname; - element.location = baseData?.data?.list?[0].location; - element.createTime = baseData?.data?.list?[0].createTime; - element.author = baseData?.data?.list?[0].memberInfo?.mid; - element.viewers = baseData?.data?.list?[0].viewers; - element.likes = baseData?.data?.list?[0].likes; - element.comments = baseData?.data?.list?[0].comments; - this.isRefresh = false; - setState(() {}); + if (baseData?.data?.list?.isNotEmpty ?? false) { + if (searchKey != null) { + articles.forEach((element) { + if (element.id == searchKey) { + element.content = jsonEncode(baseData?.data?.list?[0].subjectInfo); + element.mainTitle = baseData?.data?.list?[0].subject; + element.followed = baseData?.data?.list?[0].selfFollow; + element.liked = baseData?.data?.list?[0].selfLike; + element.authorHeadImg = baseData?.data?.list?[0].memberInfo?.avatar; + element.authorName = baseData?.data?.list?[0].memberInfo?.nickname; + element.location = baseData?.data?.list?[0].location; + element.createTime = baseData?.data?.list?[0].createTime; + element.author = baseData?.data?.list?[0].memberInfo?.mid; + element.viewers = baseData?.data?.list?[0].viewers; + element.likes = baseData?.data?.list?[0].likes; + element.comments = baseData?.data?.list?[0].comments; + this.isRefresh = false; + } + }); + setState(() {}); + } else { + if (pageNum == 1) { + articles.clear(); } - }); + baseData!.data!.list!.forEach((element) { + var article = Article(); + article.id = element.id; + article.content = jsonEncode(element.subjectInfo); + article.mainTitle = element.subject; + article.followed = element.selfFollow; + article.liked = element.selfLike; + article.authorHeadImg = element.memberInfo?.avatar; + article.authorName = element.memberInfo?.nickname; + article.location = element.location; + article.createTime = element.createTime; + article.author = element.memberInfo?.mid; + article.viewers = element.viewers; + article.likes = element.likes; + article.comments = element.comments; + articles.add(article); + }); + if ((int.tryParse(baseData.data!.total ?? "0") ?? 0) < (pageNum * 10)) { + refreshController.loadNoData(); + } + } + } } isLoadingData = false; @@ -131,7 +157,7 @@ class CommunityChildPageState extends State Widget build(BuildContext context) { super.build(context); return FutureBuilder( - future: queryCommunity(null), + future: queryCommunity(), builder: (context, position) { return Stack( alignment: Alignment.bottomRight, @@ -139,7 +165,7 @@ class CommunityChildPageState extends State SmartRefresher( controller: refreshController, enablePullDown: true, - enablePullUp: (articles.length == 0) ? false:true, + enablePullUp: articles.isNotEmpty, physics: BouncingScrollPhysics(), header: MyHeader(), footer: CustomFooter( @@ -152,7 +178,7 @@ class CommunityChildPageState extends State isLoadMore = true; setState(() {}); }, - child: (articles.length == 0) + child: (articles.isEmpty) ? NoDataView( src: "assets/image/guan_zhu.webp", isShowBtn: false, @@ -173,11 +199,10 @@ class CommunityChildPageState extends State userId: userId, isList: true, exitFull: () { - // setState(() { - // onRefresh(); - // }); - - queryCommunity(articles[position].id); + queryCommunity(searchKey: articles[position].id); + }, + removalDynamic: () { + queryCommunity().then((value) => setState(() {})); }, ), onTap: () { @@ -188,12 +213,9 @@ class CommunityChildPageState extends State "userId": userId, }, ).then((value) { - // onRefresh(); - // setState(() {}); - queryCommunity(articles[position].id); + queryCommunity(searchKey: articles[position].id); }); // setState(() {}); - }, ); }, diff --git a/lib/community/community_course.dart b/lib/community/community_course.dart index ba0a850a..76635efc 100644 --- a/lib/community/community_course.dart +++ b/lib/community/community_course.dart @@ -14,6 +14,7 @@ import 'package:huixiang/data/page.dart'; import 'package:huixiang/main.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -57,32 +58,26 @@ class _CommunityCourse extends State setState(() {}); } }); - if (apiService == null) { - SharedPreferences.getInstance().then((value) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - _onRefresh(); - }); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + _onRefresh(); } ///banner queryCourseBanner() async { - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); BaseData>? baseData = await apiService?.queryBanner({ "model": {"type": "COURSE_BANNER"}, }).catchError((onError) { refreshController.refreshFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { bannerData.clear(); @@ -122,6 +117,7 @@ class _CommunityCourse extends State refreshController.refreshFailed(); refreshController.loadFailed(); } + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (categoryId == "") { @@ -144,8 +140,10 @@ class _CommunityCourse extends State ///课程的合集列表 collectionList() async { - BaseListData? baseData = - await apiService?.collectList().catchError((onError) {}); + BaseListData? baseData = await apiService?.collectList() + .catchError((onError) { + return BaseListData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { collectList.clear(); @@ -160,8 +158,9 @@ class _CommunityCourse extends State ///合集包含的课程列表 collectCourse(collectId) async { - BaseListData? baseData = - await apiService?.collect(collectId).catchError((error) {}); + BaseListData? baseData = await apiService?.collect(collectId).catchError((error) { + return BaseListData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { if (!collectMap.containsKey(collectId)) { diff --git a/lib/community/community_details.dart b/lib/community/community_details.dart index 740f4edd..1fb60389 100644 --- a/lib/community/community_details.dart +++ b/lib/community/community_details.dart @@ -1,5 +1,6 @@ import 'dart:ui'; +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; @@ -10,15 +11,16 @@ import 'package:huixiang/data/member_comment.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; +import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; +import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/tips_dialog.dart'; import 'package:huixiang/web/web_view/comment_list.dart'; import 'package:huixiang/web/web_view/input_comment.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import '../view_widget/classic_header.dart'; -import '../view_widget/my_footer.dart'; class CommunityDetails extends StatefulWidget { final Map arguments; @@ -113,6 +115,11 @@ class _CommunityDetails extends State emojiShowing = false; }); }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); _queryMemberCommentList(true); queryDetails(businessId); } @@ -153,11 +160,10 @@ class _CommunityDetails extends State ///详情接口 queryDetails(id) async { - SharedPreferences value = await SharedPreferences.getInstance(); - BaseData
? baseData = - await apiService?.informationInfo(id).catchError((onError) { + BaseData
? baseData = await apiService?.informationInfo(id).catchError((onError) { debugPrint(onError.toString()); refreshController.refreshFailed(); + return BaseData
()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { @@ -233,9 +239,7 @@ class _CommunityDetails extends State exitFull: () { setState(() {}); }, - userId: widget.arguments != null - ? widget.arguments["userId"] - : widget.arguments["mid"], + userId: widget.arguments["userId"] ?? widget.arguments["mid"], itemCount: 3, isDetails: true, heightFun: (height) { @@ -308,9 +312,10 @@ class _CommunityDetails extends State ///给文章/活动点赞 _queryInformationLikes() async { - BaseData? baseData = await apiService - ?.informationLikes("${businessId}") - .catchError((onError) {}); + BaseData? baseData = await apiService?.informationLikes("${businessId}") + .catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { commentKey.currentState?.setState(() {}); setState(() { @@ -321,8 +326,6 @@ class _CommunityDetails extends State article?.likes = likes + 1; article?.liked = !(article?.liked ?? false); }); - } else { - // SmartDialog.showToast(baseData.msg, alignment: Alignment.center); } } @@ -333,7 +336,9 @@ class _CommunityDetails extends State "parentId": parenId, "relationalId": businessId, "relationalType": 4 - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { CommentListState? state = commentKey.currentState as CommentListState?; state?.queryMemberCommentList(); @@ -346,8 +351,7 @@ class _CommunityDetails extends State ///滑动到评论列表 _toComment() { if (commentKey.currentContext == null) return; - RenderBox? firstRenderBox = - commentKey.currentContext?.findRenderObject() as RenderBox?; + RenderBox? firstRenderBox = commentKey.currentContext?.findRenderObject() as RenderBox?; Offset? first = firstRenderBox?.localToGlobal(Offset.zero); scrollController.animateTo( (first?.dy ?? 0) + @@ -373,7 +377,9 @@ class _CommunityDetails extends State SmartDialog.show( builder: (ctx) => Tips(() { delComment(memberComment); - })); + }, + ), + ); } ///删除评论 @@ -398,17 +404,18 @@ class _CommunityDetails extends State SmartDialog.showLoading( msg: S.current.zhengzaijiazai, ); - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - BaseData>? baseData = - await apiService?.memberCommentList({ + + BaseData>? baseData = await apiService?.memberCommentList({ "pageNum": 1, "pageSize": 100, "relationalId": businessId, "relationalType": 4, - }).catchError((error) {}); + }).catchError((error) { + return BaseData>()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { commentTotal = baseData!.data?.size; - memberList = baseData!.data?.list ?? []; + memberList = baseData.data?.list ?? []; contentHeight(); if (mounted) setState(() {}); SmartDialog.dismiss(); diff --git a/lib/community/community_list.dart b/lib/community/community_list.dart index 2d820861..9ffaf803 100644 --- a/lib/community/community_list.dart +++ b/lib/community/community_list.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/comunity_comment.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/icon_text.dart'; @@ -38,11 +39,8 @@ class _CommunityList extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - if(apiService != null) - apiService = ApiService(Dio(), - context: context, token: value.getString("token")), - }); + apiService = ApiService(Dio(), + context: context, token: SharedInstance.instance.token); } ///关注/取关会员 @@ -53,8 +51,6 @@ class _CommunityList extends State { SmartDialog.showToast(isFollow ? "关注成功" : "取关成功", alignment: Alignment.center); setState(() {}); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -65,8 +61,6 @@ class _CommunityList extends State { widget.exitFull?.call(); SmartDialog.showToast("删除成功", alignment: Alignment.center); setState(() {}); - } else { - // SmartDialog.showToast(baseData.msg, alignment: Alignment.center); } } diff --git a/lib/community/community_view/class_details.dart b/lib/community/community_view/class_details.dart index 3837dcc0..a1379e97 100644 --- a/lib/community/community_view/class_details.dart +++ b/lib/community/community_view/class_details.dart @@ -13,6 +13,8 @@ import 'package:huixiang/data/course_details.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; +import 'package:huixiang/view_widget/share_dialog.dart'; import 'package:huixiang/view_widget/tips_dialog.dart'; import 'package:huixiang/web/web_view/comment_list.dart'; import 'package:huixiang/web/web_view/input_comment.dart'; @@ -21,7 +23,6 @@ import 'package:sharesdk_plugin/sharesdk_defines.dart'; import 'package:sharesdk_plugin/sharesdk_interface.dart'; import 'package:sharesdk_plugin/sharesdk_map.dart'; -import '../../view_widget/share_dialog.dart'; class ClassDetails extends StatefulWidget { final Map arguments; @@ -62,23 +63,18 @@ class _ClassDetails extends State with WidgetsBindingObserver { super.initState(); WidgetsBinding.instance.addObserver(this); commentFocus.addListener(_focusNodeListener); - if (apiService == null) { - SharedPreferences.getInstance().then((value) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - courseDetails(widget.arguments["id"]); - queryChapterList(widget.arguments["id"]); - }); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + courseDetails(widget.arguments["id"]); + queryChapterList(widget.arguments["id"]); } ///课程章节列表 queryChapterList(courseId) async { - BaseListData? baseData = - await apiService?.catalogList(courseId).catchError((onError) { + BaseListData? baseData = await apiService?.catalogList(courseId).catchError((onError) { return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -86,8 +82,7 @@ class _ClassDetails extends State with WidgetsBindingObserver { chapterList.clear(); chapterList.addAll(baseData!.data ?? []); chapterIndex = 0; - ClassDetailsVideoState? state = - videoKey.currentState as ClassDetailsVideoState?; + ClassDetailsVideoState? state = videoKey.currentState as ClassDetailsVideoState?; state?.initVideo(chapterList[chapterIndex].content?.fileUrl); // initVideo(chapterList[chapterIndex].content.fileUrl); }); @@ -97,8 +92,10 @@ class _ClassDetails extends State with WidgetsBindingObserver { ///课程详情 courseDetails(id) async { - BaseData? baseData = - await apiService?.course(id).catchError((error) {}); + BaseData? baseData = await apiService?.course(id) + .catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { course = baseData!.data; diff --git a/lib/community/community_view/community_dynamic.dart b/lib/community/community_view/community_dynamic.dart index aacb5888..dadccc0d 100644 --- a/lib/community/community_view/community_dynamic.dart +++ b/lib/community/community_view/community_dynamic.dart @@ -1,14 +1,17 @@ import 'dart:convert'; import 'package:chewie/chewie.dart'; +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:flutter_svg/svg.dart'; +import 'package:get/get.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/article.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:chewie/src/chewie_progress_colors.dart' as chewie; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/round_button.dart'; @@ -35,7 +38,7 @@ class CommunityDynamic extends StatefulWidget { CommunityDynamic( this.article, this.commentType, { - Key? key, + super.key, this.itemCount = 9, this.heightFun, this.isDetails = false, @@ -43,7 +46,7 @@ class CommunityDynamic extends StatefulWidget { this.exitFull, this.userId, this.isList = false, - }) : super(key: key); + }); @override State createState() { @@ -56,13 +59,17 @@ class _CommunityDynamic extends State { double height = 0; ApiService? apiService; - late VideoPlayerController videoPlayerController; - late ChewieController chewieAudioController; + VideoPlayerController? videoPlayerController; + ChewieController? chewieAudioController; late Chewie chewies; @override void initState() { super.initState(); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + ); initVideo(); } @@ -78,10 +85,11 @@ class _CommunityDynamic extends State { } else { videoPlayerController = VideoPlayerController.networkUrl( Uri.parse(cnt["video"]), - )..initialize().then((value) { + ); + videoPlayerController!.initialize().then((value) { chewieAudioController = ChewieController( - videoPlayerController: videoPlayerController, - aspectRatio: videoPlayerController.value.aspectRatio, + videoPlayerController: videoPlayerController!, + aspectRatio: videoPlayerController!.value.aspectRatio, //宽高比 autoPlay: false, //自动播放 @@ -97,7 +105,7 @@ class _CommunityDynamic extends State { ), autoInitialize: true, ); - chewieAudioController.addListener(_fullScreenListener); + chewieAudioController!.addListener(_fullScreenListener); if (mounted) setState(() {}); }); } @@ -106,34 +114,36 @@ class _CommunityDynamic extends State { ///关注/取关会员 _vipFollow(followId, isFollow) async { - BaseData? baseData = await apiService?.follow(followId ?? ""); + BaseData? baseData = await apiService?.follow(followId ?? "").catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { widget.exitFull?.call(); - SmartDialog.showToast(isFollow ? "关注成功" : "取关成功", - alignment: Alignment.center); + SmartDialog.showToast( + isFollow ? "关注成功" : "取关成功", + alignment: Alignment.center, + ); setState(() {}); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } ///删除动态 _deleteDynamic(id) async { - BaseData? baseData = await apiService?.deleteTrend(id); + BaseData? baseData = await apiService?.deleteTrend(id).catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { + widget.removalDynamic?.call(); widget.exitFull?.call(); SmartDialog.showToast("删除成功", alignment: Alignment.center); - setState(() {}); - } else { - // SmartDialog.showToast(baseData.msg, alignment: Alignment.center); } } ///给文章/活动点赞 _queryInformationLikes(isLikes) async { - BaseData? baseData = await apiService - ?.informationLikes("${widget.article?.id}") - .catchError((onError) {}); + BaseData? baseData = await apiService?.informationLikes("${widget.article?.id}").catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { widget.exitFull?.call(); setState(() {}); @@ -141,11 +151,15 @@ class _CommunityDynamic extends State { } goPersonalPage() async { - await Navigator.of(context).pushNamed('/router/personal_page', arguments: { - "memberId": (widget.article?.author == widget.userId) - ? "0" - : widget.article?.author, - }); + if (widget.article?.author == null || widget.article?.author == widget.userId) { + return; + } + await Navigator.of(context).pushNamed( + '/router/personal_page', + arguments: { + "memberId": widget.article?.author, + }, + ); widget.exitFull?.call(); } @@ -159,7 +173,7 @@ class _CommunityDynamic extends State { alignment: Alignment.topCenter, padding: EdgeInsets.only( left: 16.w, - top: 16.h, + top: 16, right: 16.w, ), decoration: BoxDecoration( @@ -188,16 +202,6 @@ class _CommunityDynamic extends State { children: [ GestureDetector( onTap: () { - // Navigator.push( - // context, - // MaterialPageRoute( - // builder: (context) => PhotoViewGalleryScreen( - // images: [(widget?.article?.authorHeadImg ?? "").isEmpty? - // "https://lmg.jj20.com/up/allimg/tx30/09041130358711081.jpg":widget?.article?.authorHeadImg - // ], //传入图片list - // index: 0, //传入当前点击的图片的index - // ), - // )); goPersonalPage(); }, child: MImage( @@ -220,10 +224,7 @@ class _CommunityDynamic extends State { Text( widget.article?.authorName ?? "", style: TextStyle( - fontSize: - MediaQuery.of(context).size.width >= 650 - ? 12.sp - : 15.sp, + fontSize: 15.sp, fontWeight: MyFontWeight.semi_bold, color: Color(0xFF1A1A1A), ), @@ -231,10 +232,7 @@ class _CommunityDynamic extends State { Text( widget.article?.createTime ?? "", style: TextStyle( - fontSize: - MediaQuery.of(context).size.width >= 650 - ? 10.sp - : 13.sp, + fontSize: 13.sp, fontWeight: MyFontWeight.regular, color: Color(0xFF808080), ), @@ -261,11 +259,10 @@ class _CommunityDynamic extends State { }, child: (widget.commentType == 0) ? Container( - width: 56.w, height: 25.h, alignment: Alignment.center, child: RoundButton( - height: 25.h, + height: 28, backgroup: (widget.article?.followed ?? false) ? Color(0xFFE6E6E6) : Color(0xFF32A060), @@ -276,6 +273,9 @@ class _CommunityDynamic extends State { ? S.of(context).yiguanzhu : S.of(context).guanzhu, radius: 20, + padding: EdgeInsets.symmetric( + horizontal: 10, + ), icons: Icon( (widget.article?.followed ?? false) ? Icons.check @@ -285,7 +285,8 @@ class _CommunityDynamic extends State { : Colors.white, size: 15, ), - )) + ), + ) : Padding( padding: EdgeInsets.all(20), child: Icon( @@ -302,7 +303,7 @@ class _CommunityDynamic extends State { ), widget.isList ? Text( - widget.article?.mainTitle ?? "", + widget.article?.mainTitle?.trim() ?? "", maxLines: 5, overflow: TextOverflow.ellipsis, style: TextStyle( @@ -312,7 +313,7 @@ class _CommunityDynamic extends State { ), ) : Text( - widget.article?.mainTitle ?? "", + widget.article?.mainTitle?.trim() ?? "", style: TextStyle( color: Color(0xFF1A1A1A), fontWeight: MyFontWeight.regular, @@ -325,7 +326,10 @@ class _CommunityDynamic extends State { ), if (widget.article?.location != "") Padding( - padding: EdgeInsets.only(bottom: 7), + padding: EdgeInsets.only( + top: 7, + bottom: widget.isList ? 0 : 12, + ), child: Row( children: [ Icon( @@ -357,18 +361,39 @@ class _CommunityDynamic extends State { ), if (!widget.isDetails) Container( - // padding: EdgeInsets.only(bottom: 16), + padding: EdgeInsets.only(bottom: 12), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( - child: Container( - padding: EdgeInsets.only(bottom: 16.h), + child: Row( + children: [ + SvgPicture.asset( + "assets/svg/liulanliang.svg", + width: 16, + height: 16, + ), + SizedBox( + width: 5.w, + ), + Text( + "${widget.article?.viewers}", + style: TextStyle( + fontSize: 14.sp, + fontFamily: 'JDZhengHT', + fontWeight: MyFontWeight.regular, + color: Color(0xFF1A1A1A), + ), + ), + ], + ), + ), + Expanded( child: Row( children: [ SvgPicture.asset( - "assets/svg/liulanliang.svg", + "assets/svg/pinglun.svg", width: 16, height: 16, ), @@ -376,7 +401,7 @@ class _CommunityDynamic extends State { width: 5.w, ), Text( - "${widget.article?.viewers}", + "${widget.article?.comments ?? 0}", style: TextStyle( fontSize: 14.sp, fontFamily: 'JDZhengHT', @@ -386,32 +411,7 @@ class _CommunityDynamic extends State { ), ], ), - ), ), - Expanded( - child: Container( - padding: EdgeInsets.only(bottom: 16.h), - child: Row( - children: [ - SvgPicture.asset( - "assets/svg/pinglun.svg", - width: 16, - height: 16, - ), - SizedBox( - width: 5.w, - ), - Text( - "${widget.article?.comments ?? 0}", - style: TextStyle( - fontSize: 14.sp, - fontFamily: 'JDZhengHT', - fontWeight: MyFontWeight.regular, - color: Color(0xFF1A1A1A), - ), - ), - ], - ))), Expanded( child: GestureDetector( behavior: HitTestBehavior.opaque, @@ -423,40 +423,36 @@ class _CommunityDynamic extends State { widget.article?.liked ?? false); }); }, - child: Container( - padding: EdgeInsets.only(bottom: 16.h), - child: Row( - children: [ - (widget.article?.liked ?? false) - ? Image.asset( - "assets/image/icon_like.webp", - width: 16, - height: 16, - ) - : Image.asset( - "assets/image/icon_like_h.webp", - width: 16, - height: 16, - ), - SizedBox( - width: 5.w, - ), - Text( - "${widget.article?.likes ?? 0}", - style: TextStyle( - fontSize: 14.sp, - fontFamily: 'JDZhengHT', - fontWeight: MyFontWeight.regular, - color: Color(0xFF1A1A1A), - ), + child: Row( + children: [ + (widget.article?.liked ?? false) + ? Image.asset( + "assets/image/icon_like.webp", + width: 16, + height: 16, + ) + : Image.asset( + "assets/image/icon_like_h.webp", + width: 16, + height: 16, + ), + SizedBox( + width: 5.w, + ), + Text( + "${widget.article?.likes ?? 0}", + style: TextStyle( + fontSize: 14.sp, + fontFamily: 'JDZhengHT', + fontWeight: MyFontWeight.regular, + color: Color(0xFF1A1A1A), ), - ], - ), + ), + ], ), ), ), - if ((widget.article?.author != (widget.userId ?? "")) && - widget.commentType == 0) + if (widget.commentType == 0) Expanded( child: GestureDetector( behavior: HitTestBehavior.opaque, @@ -468,9 +464,8 @@ class _CommunityDynamic extends State { child: Container( padding: EdgeInsets.only( top: 3.h, - bottom: 16.h, ), - alignment: Alignment.center, + alignment: Alignment.centerRight, // color: Colors.red, child: Icon( Icons.more_horiz, @@ -486,7 +481,7 @@ class _CommunityDynamic extends State { ), ), Container( - height: 16.h, + height: 16, color: Color(0xFFF7F7F7), ), ], @@ -534,7 +529,8 @@ class _CommunityDynamic extends State { print("share!$state"); }); }); - }); + }, + ); } String buildShareUrl() { @@ -552,38 +548,37 @@ class _CommunityDynamic extends State { cnt["images"] != null && cnt["images"].length > 0) { if (cnt["images"].length == 1) { - itemWidget = Container( - child: InkWell( - onTap: () { - // ImagePickers.previewImages(subjectInfo.images,0); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PhotoViewGalleryScreen( - images: cnt["images"], //传入图片list - index: 0, //传入当前点击的图片的index - ), - ), - ); - }, - child: MImage( - cnt["images"][0], - fit: BoxFit.contain, - radius: BorderRadius.circular(2), - height: MediaQuery.of(context).size.width / 1.5, - errorSrc: "assets/image/default_2_1.webp", - fadeSrc: "assets/image/default_2_1.webp", - )), + itemWidget = InkWell( + onTap: () { + // ImagePickers.previewImages(subjectInfo.images,0); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PhotoViewGalleryScreen( + images: cnt["images"], //传入图片list + index: 0, //传入当前点击的图片的index + ), + ), + ); + }, + child: Container( + constraints: BoxConstraints( + maxHeight: MediaQuery.of(context).size.width / 1.5, + ), + child: MImage( + cnt["images"][0], + radius: BorderRadius.circular(2), + errorSrc: "assets/image/default_2_1.webp", + fadeSrc: "assets/image/default_2_1.webp", + ), + ), ); } else { itemWidget = GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: - (cnt["images"].length == 2 || cnt["images"].length == 4) - ? 2 - : 3, - crossAxisSpacing: 12.w, - mainAxisSpacing: 12.w, + crossAxisCount: (cnt["images"].length == 2 || cnt["images"].length == 4) ? 2 : 3, + crossAxisSpacing: 12, + mainAxisSpacing: 12, childAspectRatio: 1, ), padding: EdgeInsets.zero, @@ -618,14 +613,12 @@ class _CommunityDynamic extends State { itemCount: cnt["images"].length, ); } - } else if (cnt["type"] == "video" && - cnt["video"] != null && - cnt["video"].isNotEmpty) { + } else if (cnt["type"] == "video" && cnt["video"] != null && cnt["video"].isNotEmpty) { itemWidget = videoWidget( MediaQuery.of(context).size.width - 32, videoPlayerController != null ? (MediaQuery.of(context).size.width - 32) / - videoPlayerController.value.aspectRatio + videoPlayerController!.value.aspectRatio : MediaQuery.of(context).size.width / 2, cnt["video"].replaceAll(".mp4", "_poster.jpg"), ); @@ -636,7 +629,7 @@ class _CommunityDynamic extends State { mainAxisSize: MainAxisSize.min, children: [ SizedBox( - height: 16.h, + height: 16, ), itemWidget, ], @@ -646,11 +639,11 @@ class _CommunityDynamic extends State { @override void dispose() { super.dispose(); - chewieAudioController.pause(); - chewieAudioController.dispose(); + chewieAudioController?.pause(); + chewieAudioController?.dispose(); - videoPlayerController.pause(); - videoPlayerController.dispose(); + videoPlayerController?.pause(); + videoPlayerController?.dispose(); } Widget videoWidget(double width, double height, src) { @@ -664,7 +657,7 @@ class _CommunityDynamic extends State { width: width, height: height, child: chewies = Chewie( - controller: chewieAudioController, + controller: chewieAudioController!, ), ) : Container( @@ -683,7 +676,7 @@ class _CommunityDynamic extends State { child: MImage( src, aspectRatio: videoPlayerController != null - ? videoPlayerController.value.aspectRatio + ? videoPlayerController!.value.aspectRatio : (width / 7 * 5), fit: BoxFit.cover, errorSrc: "assets/image/default_2_1.webp", @@ -704,7 +697,7 @@ class _CommunityDynamic extends State { } Future _fullScreenListener() async { - if (!chewieAudioController.isFullScreen) { + if (!(chewieAudioController?.isFullScreen ?? false)) { Future.delayed(Duration(seconds: 1), () { widget.exitFull?.call(); }); @@ -793,19 +786,22 @@ class _CommunityDynamic extends State { return buildBottomSheetWidget(context); }, backgroundColor: Colors.transparent, - context: context); + context: context, + ); } Widget buildBottomSheetWidget(BuildContext context) { return Container( padding: EdgeInsets.all(16), - decoration: new BoxDecoration( + decoration: BoxDecoration( color: Colors.white, borderRadius: new BorderRadius.only( topLeft: const Radius.circular(25.0), - topRight: const Radius.circular(25.0))), + topRight: const Radius.circular(25.0), + ), + ), child: Container( - height: 130.h, + height: ("${widget.article?.author ?? ""}" == "${SharedInstance.instance.userId}") ? 145.h : 100.h, child: Column( children: [ GestureDetector( @@ -845,7 +841,8 @@ class _CommunityDynamic extends State { ), ], ), - )), + ), + ), Container( margin: EdgeInsets.symmetric(vertical: 12), height: 1.h, @@ -855,8 +852,7 @@ class _CommunityDynamic extends State { behavior: HitTestBehavior.translucent, onTap: () { setState(() { - Navigator.of(context) - .popAndPushNamed('/router/report_page', arguments: { + Navigator.of(context).popAndPushNamed('/router/report_page', arguments: { "userName": widget.article?.authorName ?? "", "authorId": widget.article?.author ?? "", }); @@ -889,7 +885,50 @@ class _CommunityDynamic extends State { ], ), ), - ) + ), + if (("${widget.article?.author ?? ""}" == "${SharedInstance.instance.userId}")) ...[ + Container( + margin: EdgeInsets.symmetric( + vertical: 12, + ), + height: 1.h, + color: Color(0xFFF7F7F7), + ), + GestureDetector( + behavior: HitTestBehavior.translucent, + onTap: () { + Navigator.of(context).pop(); + showDeleteDialog(); + }, + child: Container( + width: double.infinity, + padding: EdgeInsets.symmetric(vertical: 5.h), + child: Row( + children: [ + SizedBox( + width: 4.w, + ), + SvgPicture.asset( + "assets/svg/ju_b.svg", + width: 20, + height: 20, + ), + SizedBox( + width: 15.w, + ), + Text( + S.of(context).shanchu, + style: TextStyle( + fontSize: 17.sp, + fontWeight: MyFontWeight.medium, + color: Color(0xFF1A1A1A), + ), + ), + ], + ), + ), + ), + ], ], ), ), @@ -908,4 +947,5 @@ class _CommunityDynamic extends State { widget.heightFun?.call(height); print("height: $height"); } + } diff --git a/lib/community/community_view/course_banner.dart b/lib/community/community_view/course_banner.dart index 786c115f..cf56c9ab 100644 --- a/lib/community/community_view/course_banner.dart +++ b/lib/community/community_view/course_banner.dart @@ -22,11 +22,10 @@ class CourseBanner extends StatefulWidget { } class _CourseBanner extends State { - ApiService? apiService; + final RefreshController refreshController = RefreshController(); List bannerData = []; - @override Widget build(BuildContext context) { return Container( @@ -76,20 +75,26 @@ class _CourseBanner extends State { bannerClick(BannerData bannerData) async { switch (bannerData.contentType) { case 1: - Navigator.of(context).pushNamed('/router/integral_store_page', - arguments: {"goodsId": bannerData.content}); + Navigator.of(context).pushNamed( + '/router/integral_store_page', + arguments: {"goodsId": bannerData.content}, + ); break; case 2: - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "activityId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "activityId": bannerData.content, + }, + ); break; case 3: - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "articleId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "articleId": bannerData.content, + }, + ); break; case 4: String? router = bannerData.content; @@ -106,10 +111,12 @@ class _CourseBanner extends State { } break; case 5: - Navigator.of(context) - .pushNamed('/router/class_details', arguments: { - "id": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/class_details', + arguments: { + "id": bannerData.content, + }, + ); break; case 7: String? router = bannerData.content; diff --git a/lib/community/community_view/home_class.dart b/lib/community/community_view/home_class.dart index ff0ef95d..2af3c0e3 100644 --- a/lib/community/community_view/home_class.dart +++ b/lib/community/community_view/home_class.dart @@ -21,7 +21,6 @@ class HomeClass extends StatefulWidget { } class _HomeClass extends State { - ApiService? apiService; Position? latLng; final TextEditingController editingController = TextEditingController(); diff --git a/lib/community/headlines/activity_top_list.dart b/lib/community/headlines/activity_top_list.dart index 274bcf5e..963816fd 100644 --- a/lib/community/headlines/activity_top_list.dart +++ b/lib/community/headlines/activity_top_list.dart @@ -1,8 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:geolocator/geolocator.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/article.dart'; -import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -19,8 +17,6 @@ class ActivityTopList extends StatefulWidget { } class _ActivityTopList extends State { - ApiService? apiService; - Position? latLng; final TextEditingController editingController = TextEditingController(); diff --git a/lib/community/headlines/article_list.dart b/lib/community/headlines/article_list.dart index 5bb5c71c..5bbc3f9a 100644 --- a/lib/community/headlines/article_list.dart +++ b/lib/community/headlines/article_list.dart @@ -4,6 +4,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/article.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -28,10 +29,10 @@ class _ArticleList extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, token: value.getString("token")), - }); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + ); } @override @@ -53,7 +54,8 @@ class _ArticleList extends State { fontWeight: MyFontWeight.semi_bold, color: Colors.black, ), - )), + ), + ), ListView.builder( padding: EdgeInsets.zero, itemCount: widget.articles.length, @@ -76,7 +78,8 @@ class _ArticleList extends State { }, ), ], - )); + ), + ); } Widget articleItem(Article articles, position) { @@ -125,21 +128,6 @@ class _ArticleList extends State { mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ - // Expanded( - // child: Text( - // widget.articles != null - // ? widget.articles[position]?.author?.name ?? "" - // : "", - // overflow: TextOverflow.ellipsis, - // maxLines: 1, - // style: TextStyle( - // fontSize: 12.sp, - // fontWeight: MyFontWeight.medium, - // color: Color(0xFF8E8E8E), - // ), - // ), - // ), - // SizedBox(width: 8.w), Image.asset( "assets/image/browse.webp", width: 14, @@ -171,7 +159,7 @@ class _ArticleList extends State { ), ), ], - ) + ), ], ), ), diff --git a/lib/community/headlines/article_page.dart b/lib/community/headlines/article_page.dart index 39e7d62d..1ab1573f 100644 --- a/lib/community/headlines/article_page.dart +++ b/lib/community/headlines/article_page.dart @@ -1,3 +1,4 @@ +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; @@ -14,6 +15,7 @@ import 'package:huixiang/main.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/store_title_tab.dart'; @@ -60,6 +62,10 @@ class _ArticlePage extends State setState(() {}); } }); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + ); queryArticleList(false); queryArticleList(true); queryHeadlinesBanner(); @@ -78,6 +84,7 @@ class _ArticlePage extends State "model": {"type": "INFORMATION"}, }).catchError((onError) { refreshController.refreshFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { bannerData.clear(); @@ -108,6 +115,7 @@ class _ArticlePage extends State }).catchError((onError) { refreshController.refreshFailed(); refreshController.loadFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { refreshController.refreshCompleted(); @@ -139,8 +147,7 @@ class _ArticlePage extends State ///文章合集列表 queryHeadlinesList() async { - BaseListData? baseData = - await apiService?.headlinesList().catchError((onError) { + BaseListData? baseData = await apiService?.headlinesList().catchError((onError) { return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -248,7 +255,8 @@ class _ArticlePage extends State fontWeight: MyFontWeight.semi_bold, color: Colors.black, ), - )), + ), + ), ///头条合集列表 HeadlinesCollection(headlines, articles), diff --git a/lib/community/headlines/headlines_banner.dart b/lib/community/headlines/headlines_banner.dart index 6a5f1b10..354c06ce 100644 --- a/lib/community/headlines/headlines_banner.dart +++ b/lib/community/headlines/headlines_banner.dart @@ -22,7 +22,7 @@ class HeadlinesBanner extends StatefulWidget { } class _HeadlinesBanner extends State { - ApiService? apiService; + final RefreshController refreshController = RefreshController(); List bannerData = []; @@ -73,20 +73,26 @@ class _HeadlinesBanner extends State { bannerClick(BannerData bannerData) async { switch (bannerData.contentType) { case 1: - Navigator.of(context).pushNamed('/router/integral_store_page', - arguments: {"goodsId": bannerData.content}); + Navigator.of(context).pushNamed( + '/router/integral_store_page', + arguments: {"goodsId": bannerData.content}, + ); break; case 2: - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "activityId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "activityId": bannerData.content, + }, + ); break; case 3: - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "articleId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "articleId": bannerData.content, + }, + ); break; case 4: String? router = bannerData.content; @@ -103,10 +109,12 @@ class _HeadlinesBanner extends State { } break; case 5: - Navigator.of(context) - .pushNamed('/router/class_details', arguments: { - "id": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/class_details', + arguments: { + "id": bannerData.content, + }, + ); break; case 7: String? router = bannerData.content; diff --git a/lib/community/headlines/headlines_collection.dart b/lib/community/headlines/headlines_collection.dart index a8048029..2e215080 100644 --- a/lib/community/headlines/headlines_collection.dart +++ b/lib/community/headlines/headlines_collection.dart @@ -21,7 +21,7 @@ class HeadlinesCollection extends StatefulWidget { } class _HeadlinesCollection extends State { - ApiService? apiService; + Position? latLng; final TextEditingController editingController = TextEditingController(); diff --git a/lib/community/headlines/headlines_column_details.dart b/lib/community/headlines/headlines_column_details.dart index 0bd6ebc6..5504d2ad 100644 --- a/lib/community/headlines/headlines_column_details.dart +++ b/lib/community/headlines/headlines_column_details.dart @@ -1,3 +1,4 @@ +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:huixiang/data/headlines_details.dart'; import 'package:huixiang/generated/l10n.dart'; @@ -8,6 +9,7 @@ import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -39,13 +41,19 @@ class _HeadlinesColumnDetails extends State void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + ); _onRefresh(); } ///文章合集详情 queryHeadlinesDetails(id) async { - BaseData? baseData = - await apiService?.headlinesDetails(id).catchError((error) {}); + BaseData? baseData = await apiService?.headlinesDetails(id) + .catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { headlinesListDetails = baseData!.data; @@ -66,6 +74,7 @@ class _HeadlinesColumnDetails extends State }).catchError((onError) { refreshController.refreshFailed(); refreshController.loadFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { refreshController.refreshCompleted(); @@ -239,10 +248,8 @@ class _HeadlinesColumnDetails extends State child: Column( children: [ Row( - mainAxisAlignment: - MainAxisAlignment.start, - crossAxisAlignment: - CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "简介:", @@ -272,7 +279,7 @@ class _HeadlinesColumnDetails extends State color: Colors.black, ), ), - ) + ), ], ), SizedBox(height: 3.h), @@ -293,8 +300,7 @@ class _HeadlinesColumnDetails extends State S.of(context).gengduo, style: TextStyle( fontSize: 12.sp, - fontWeight: - MyFontWeight.regular, + fontWeight: MyFontWeight.regular, color: Colors.black, ), ), @@ -325,10 +331,12 @@ class _HeadlinesColumnDetails extends State itemBuilder: (context, position) { return GestureDetector( onTap: () { - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "articleId": articles[position].id - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "articleId": articles[position].id + }, + ); int viewers = articles[position].viewers ?? 0; articles[position].viewers = (viewers + 1); setState(() {}); @@ -378,8 +386,7 @@ class _HeadlinesColumnDetails extends State children: [ Expanded( child: Container( - height: - MediaQuery.of(context).size.width >= 650 ? 133.h : 105, + height: MediaQuery.of(context).size.width >= 650 ? 133.h : 105, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, @@ -397,34 +404,22 @@ class _HeadlinesColumnDetails extends State ), SizedBox(height: 6.h), Expanded( - child: Text( - articles.viceTitle ?? "", - overflow: TextOverflow.ellipsis, - maxLines: 1, - style: TextStyle( - fontSize: 12.sp, - height: 1.2.h, - fontWeight: MyFontWeight.regular, - color: Color(0xFF353535), + child: Text( + articles.viceTitle ?? "", + overflow: TextOverflow.ellipsis, + maxLines: 1, + style: TextStyle( + fontSize: 12.sp, + height: 1.2.h, + fontWeight: MyFontWeight.regular, + color: Color(0xFF353535), + ), ), - )), + ), Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ - // Expanded( - // child: Text( - // articles?.author?.name ?? "", - // overflow: TextOverflow.ellipsis, - // maxLines: 1, - // style: TextStyle( - // fontSize: 12.sp, - // fontWeight: MyFontWeight.medium, - // color: Color(0xFF8E8E8E), - // ), - // ), - // ), - // SizedBox(width: 8), Image.asset( "assets/image/browse.webp", width: 14, @@ -432,14 +427,15 @@ class _HeadlinesColumnDetails extends State color: Color(0xFF808080), ), Expanded( - child: Text( - "${articles.viewers}" ?? "", - style: TextStyle( - fontSize: 12.sp, - fontWeight: MyFontWeight.regular, - color: Color(0xFF8D8D8D), + child: Text( + "${articles.viewers}" ?? "", + style: TextStyle( + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + color: Color(0xFF8D8D8D), + ), ), - )), + ), Expanded( child: Text( articles.createTime?.split(":")[0] ?? "", @@ -449,7 +445,7 @@ class _HeadlinesColumnDetails extends State color: Color(0xFF8D8D8D), ), ), - ) + ), ], ), ], diff --git a/lib/community/new_community_details.dart b/lib/community/new_community_details.dart index 9296b66d..9391ba66 100644 --- a/lib/community/new_community_details.dart +++ b/lib/community/new_community_details.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:ui'; +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -13,6 +14,7 @@ import 'package:huixiang/data/page.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/round_button.dart'; @@ -66,15 +68,15 @@ class _NewCommunityDetails extends State userId = widget.arguments?["userId"]; WidgetsBinding.instance.addObserver(this); commentFocus.addListener(_focusNodeListener); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); queryDetails(commentsId); } ///详情接口 queryDetails(id) async { - SharedPreferences value = await SharedPreferences.getInstance(); - BaseData
? baseData = - await apiService?.informationInfo(id).catchError((onError) { + BaseData
? baseData = await apiService?.informationInfo(id).catchError((onError) { debugPrint(onError.toString()); + return BaseData
()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { @@ -90,8 +92,6 @@ class _NewCommunityDetails extends State SmartDialog.showToast(isFollow ? "关注成功" : "取关成功", alignment: Alignment.center); setState(() {}); - } else { - // SmartDialog.showToast(baseData.msg, alignment: Alignment.center); } } @@ -436,7 +436,8 @@ class _NewCommunityDetails extends State height: MediaQuery.of(context).size.width, errorSrc: "assets/image/default_2_1.webp", fadeSrc: "assets/image/default_2_1.webp", - )), + ), + ), ); } else { itemWidget = GridView.builder( @@ -520,9 +521,10 @@ class _NewCommunityDetails extends State ///给文章/活动点赞 _queryInformationLikes() async { - BaseData? baseData = await apiService - ?.informationLikes("${commentsId}") - .catchError((onError) {}); + BaseData? baseData = await apiService?.informationLikes("${commentsId}") + .catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { commentKey.currentState?.setState(() {}); setState(() { @@ -533,8 +535,6 @@ class _NewCommunityDetails extends State article?.likes = likes + 1; article?.liked = !(article?.liked ?? false); }); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -545,7 +545,9 @@ class _NewCommunityDetails extends State "parentId": parenId, "relationalId": commentsId, "relationalType": 4 - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { CommentListState? state = commentKey.currentState as CommentListState?; state?.queryMemberCommentList(); @@ -585,7 +587,9 @@ class _NewCommunityDetails extends State SmartDialog.show( builder: (ctx) => Tips(() { delComment(memberComment); - })); + }, + ), + ); } ///删除评论 @@ -606,14 +610,14 @@ class _NewCommunityDetails extends State ///评论列表 _queryMemberCommentList() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - BaseData>? baseData = - await apiService?.memberCommentList({ + BaseData>? baseData = await apiService?.memberCommentList({ "pageNum": 1, "pageSize": 100, "relationalId": commentsId, "relationalType": 4, - }).catchError((error) {}); + }).catchError((error) { + return BaseData>()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { commentTotal = baseData?.data?.size; memberList = baseData?.data?.list ?? []; diff --git a/lib/community/order_page.dart b/lib/community/order_page.dart index 9f5d05aa..33431ab2 100644 --- a/lib/community/order_page.dart +++ b/lib/community/order_page.dart @@ -29,6 +29,7 @@ class _OrderPage extends State with SingleTickerProviderStateMixin,Au @override Widget build(BuildContext context) { + super.build(context); return DefaultTabController( length: 4, child: Scaffold( diff --git a/lib/community/photo_view_gallery_screen.dart b/lib/community/photo_view_gallery_screen.dart index 2fad2c08..79503613 100644 --- a/lib/community/photo_view_gallery_screen.dart +++ b/lib/community/photo_view_gallery_screen.dart @@ -21,18 +21,19 @@ class PhotoViewGalleryScreen extends StatefulWidget { } class _PhotoViewGalleryScreenState extends State { - int currentIndex=0; + int currentIndex = 0; @override void initState() { - // TODO: implement initState + currentIndex = widget.index; super.initState(); - currentIndex=widget.index; } + File fileFromDocsDir(String filename) { String pathName = p.join(ImgCachePath.instance.path, filename); return File(pathName); } + @override Widget build(BuildContext context) { return Scaffold( diff --git a/lib/community/release_dynamic.dart b/lib/community/release_dynamic.dart index 95089f5c..9c9ea893 100644 --- a/lib/community/release_dynamic.dart +++ b/lib/community/release_dynamic.dart @@ -8,6 +8,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/address.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:image_pickers/image_pickers.dart'; @@ -38,14 +39,12 @@ class _ReleaseDynamic extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - showLoading: false, - ); - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false, + ); } @override @@ -238,7 +237,8 @@ class _ReleaseDynamic extends State { isDestructiveAction: true, ), ); - }); + }, + ); } ///显示图片选择方式 @@ -272,7 +272,8 @@ class _ReleaseDynamic extends State { isDestructiveAction: true, ), ); - }); + }, + ); } Widget addImageItem() { @@ -440,7 +441,8 @@ class _ReleaseDynamic extends State { ), ], ), - )), + ), + ), addressController.text == "" ? Container() : GestureDetector( @@ -469,7 +471,8 @@ class _ReleaseDynamic extends State { height: 5, ) ], - )); + ), + ); } } diff --git a/lib/community/report/report_notice.dart b/lib/community/report/report_notice.dart index 499279c1..ab449db6 100644 --- a/lib/community/report/report_notice.dart +++ b/lib/community/report/report_notice.dart @@ -14,7 +14,7 @@ class ReportNotice extends StatefulWidget { } class _ReportNotice extends State { - ApiService? apiService; + int checkIndex = 0; @override @@ -35,7 +35,9 @@ class _ReportNotice extends State { body: Container( width: double.infinity, color: Color(0xFFFFFFFFF), - padding: EdgeInsets.only(left: 16, top: 10, right: 16), + padding: EdgeInsets.only( + left: 16, top: 10, right: 16, + ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/community/report/report_page.dart b/lib/community/report/report_page.dart index 8e2040cf..8dc23af1 100644 --- a/lib/community/report/report_page.dart +++ b/lib/community/report/report_page.dart @@ -1,10 +1,11 @@ - +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -32,13 +33,20 @@ class _ReportPage extends State { super.initState(); userName = widget.arguments?['userName']; authorId = widget.arguments?['authorId']; + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); } report() async { BaseData? baseData = await apiService?.complaint({ "content": checkIndex == 9 ? editingController.text : textCon, "informationId": authorId, - }).catchError((onError) {}); + }).catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { Navigator.of(context).popAndPushNamed('/router/report_success'); } else { @@ -70,12 +78,16 @@ class _ReportPage extends State { Container( width: double.infinity, color: Color(0XFFFFFFFF), - padding: EdgeInsets.only(bottom: 4, left: 16, right: 16), + padding: EdgeInsets.only( + bottom: 4, + left: 16, + right: 16, + ), child: Text.rich( TextSpan( children: [ TextSpan( - text:S.of(context).jubao, + text: S.of(context).jubao, style: TextStyle( fontSize: 16.sp, fontWeight: MyFontWeight.medium, @@ -106,70 +118,78 @@ class _ReportPage extends State { SizedBox(height: 12), if (checkIndex == 9) Container( - width: double.infinity, - height: 186.h, - margin: - EdgeInsets.only(right: 16, left: 40, bottom: 100), - decoration: new BoxDecoration( - color: Color(0xFFF7F7F7), - borderRadius: BorderRadius.circular(4.0), - ), - child: Container( - margin: EdgeInsets.fromLTRB(20.w, 5.h, 20.w, 0), - alignment: Alignment.topLeft, - child: TextField( - maxLines: 5, - controller: editingController, - onChanged: (value) { - setState(() { - textLength = value.length; - }); - }, - maxLength: 100, - decoration: InputDecoration( - border: InputBorder.none, - hintText: S.of(context).jubaoyuanyin, - hintStyle: TextStyle( - fontSize: 12.sp, - height: 1.2, - fontWeight: MyFontWeight.regular, - color: Color(0xFF999999), - ), + width: double.infinity, + height: 186.h, + margin: EdgeInsets.only( + right: 16, + left: 40, + bottom: 100, + ), + decoration: new BoxDecoration( + color: Color(0xFFF7F7F7), + borderRadius: BorderRadius.circular(4.0), + ), + child: Container( + margin: EdgeInsets.fromLTRB(20.w, 5.h, 20.w, 0), + alignment: Alignment.topLeft, + child: TextField( + maxLines: 5, + controller: editingController, + onChanged: (value) { + setState(() { + textLength = value.length; + }); + }, + maxLength: 100, + decoration: InputDecoration( + border: InputBorder.none, + hintText: S.of(context).jubaoyuanyin, + hintStyle: TextStyle( + fontSize: 12.sp, + height: 1.2, + fontWeight: MyFontWeight.regular, + color: Color(0xFF999999), ), ), - )) + ), + ), + ) ], ), ), Align( - alignment: Alignment.bottomCenter, - child: Container( - width: double.infinity, - height: 95, - child: Column( - children: [ - GestureDetector( - onTap: () { - Navigator.of(context) - .pushNamed('/router/report_notice'); - }, - child: Container( - alignment: Alignment.bottomCenter, - margin: EdgeInsets.only(bottom: 25), - child: Text( - S.of(context).toushuxuzhi, - style: TextStyle( - fontSize: 14.sp, - fontWeight: MyFontWeight.regular, - color: Color(0xFF3C425C), - ), - ), - )), - Expanded( - child: GestureDetector( + alignment: Alignment.bottomCenter, + child: Container( + width: double.infinity, + height: 95, + child: Column( + children: [ + GestureDetector( + onTap: () { + Navigator.of(context) + .pushNamed('/router/report_notice'); + }, + child: Container( + alignment: Alignment.bottomCenter, + margin: EdgeInsets.only(bottom: 25), + child: Text( + S.of(context).toushuxuzhi, + style: TextStyle( + fontSize: 14.sp, + fontWeight: MyFontWeight.regular, + color: Color(0xFF3C425C), + ), + ), + ), + ), + Expanded( + child: GestureDetector( onTap: () { - if(checkIndex == 9 && editingController.text == ""){ - SmartDialog.showToast("请输入举报原因", alignment: Alignment.center); + if (checkIndex == 9 && editingController.text == "") { + SmartDialog.showToast( + "请输入举报原因", + alignment: Alignment.center, + ); return; } report(); @@ -191,10 +211,12 @@ class _ReportPage extends State { ), ), ), - )) - ], - ), - )) + ), + ), + ], + ), + ), + ), ], ), ), @@ -203,45 +225,50 @@ class _ReportPage extends State { Widget reportContent() { return Container( - width: double.infinity, - padding: EdgeInsets.only(left: 16, right: 16, top: 20), - child: Column( - children: [ - content("色情低俗", 1), - SizedBox( - height: 18, - ), - content("政治宗教", 2), - SizedBox( - height: 18, - ), - content("广告骚扰", 3), - SizedBox( - height: 18, - ), - content("虚假欺骗", 4), - SizedBox( - height: 18, - ), - content("侵权(诽谤、抄袭、冒用)", 5), - SizedBox( - height: 18, - ), - content("不良封面/标题", 6), - SizedBox( - height: 18, - ), - content("赌博诈骗", 7), - SizedBox( - height: 18, - ), - content("违禁内容(暴利恐怖、令人不适、宣言仇恨)", 8), - SizedBox( - height: 18, - ), - content("其他", 9), - ], - )); + width: double.infinity, + padding: EdgeInsets.only( + left: 16, + right: 16, + top: 20, + ), + child: Column( + children: [ + content("色情低俗", 1), + SizedBox( + height: 18, + ), + content("政治宗教", 2), + SizedBox( + height: 18, + ), + content("广告骚扰", 3), + SizedBox( + height: 18, + ), + content("虚假欺骗", 4), + SizedBox( + height: 18, + ), + content("侵权(诽谤、抄袭、冒用)", 5), + SizedBox( + height: 18, + ), + content("不良封面/标题", 6), + SizedBox( + height: 18, + ), + content("赌博诈骗", 7), + SizedBox( + height: 18, + ), + content("违禁内容(暴利恐怖、令人不适、宣言仇恨)", 8), + SizedBox( + height: 18, + ), + content("其他", 9), + ], + ), + ); } var checkIndex = 0; @@ -263,33 +290,34 @@ class _ReportPage extends State { Widget content(textContext, var index) { return GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - setState(() { - checkIndex = index; - textCon = textContext; - }); - }, - child: Container( - alignment: Alignment.center, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - checkView(index), - Container(), - Expanded( - child: Text( - textContext, - style: TextStyle( - fontSize: 16.sp, - color: Color(0xFF353535), - fontWeight: MyFontWeight.regular, - ), + behavior: HitTestBehavior.opaque, + onTap: () { + setState(() { + checkIndex = index; + textCon = textContext; + }); + }, + child: Container( + alignment: Alignment.center, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + checkView(index), + Container(), + Expanded( + child: Text( + textContext, + style: TextStyle( + fontSize: 16.sp, + color: Color(0xFF353535), + fontWeight: MyFontWeight.regular, ), - ) - ], - ), - )); + ), + ), + ], + ), + ), + ); } } diff --git a/lib/community/report/report_success.dart b/lib/community/report/report_success.dart index e76f70e2..3135ce14 100644 --- a/lib/community/report/report_success.dart +++ b/lib/community/report/report_success.dart @@ -15,7 +15,7 @@ class ReportSuccess extends StatefulWidget { } class _ReportSuccess extends State { - ApiService? apiService; + int checkIndex = 0; @override diff --git a/lib/community/share_trends.dart b/lib/community/share_trends.dart index 9c8f1788..24a71bf3 100644 --- a/lib/community/share_trends.dart +++ b/lib/community/share_trends.dart @@ -10,6 +10,7 @@ import 'package:huixiang/data/article.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:flutter/cupertino.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../generated/l10n.dart'; import '../../utils/font_weight.dart'; @@ -27,7 +28,7 @@ class ShareTrends extends StatefulWidget { } } -class _ShareTrends extends State{ +class _ShareTrends extends State { ApiService? apiService; bool topSetting = false; final TextEditingController textController = TextEditingController(); @@ -42,17 +43,14 @@ class _ShareTrends extends State{ ///详情接口 queryDetails(id) async { - SharedPreferences value = await SharedPreferences.getInstance(); - if (apiService == null) - apiService = ApiService( - Dio(), + apiService ??= ApiService(Dio(), context: context, - token: value.getString("token"), - showLoading: true - ); - BaseData
? baseData = - await apiService?.informationInfo(id).catchError((onError) { + token: SharedInstance.instance.token, + showLoading: true, + ); + BaseData
? baseData = await apiService?.informationInfo(id).catchError((onError) { debugPrint(onError.toString()); + return BaseData
()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { @@ -65,34 +63,13 @@ class _ShareTrends extends State{ Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xFFF9FAF7), - // appBar: MyAppBar( - // title:"转发", - // titleColor: Colors.black, - // titleSize: 18.sp, - // background: Colors.white, - // leading: false, - // leadingColor: Colors.black, - // actions: [ - // Container( - // alignment: Alignment.center , - // color: Color(0xFF32A060), - // margin:EdgeInsets.only(right: 16.w) , - // child: Text( - // S.of(context).fabu, - // style: TextStyle( - // color: Colors.white, - // fontSize:12.sp, - // fontWeight: MyFontWeight.regular, - // ), - // ), - // ) - // ], - // ), body: Container( child: Column( children: [ Container( - padding:EdgeInsets.only(top: MediaQuery.of(context).padding.top+11.h,bottom:14.w), + padding: EdgeInsets.only( + top: MediaQuery.of(context).padding.top + 11.h, bottom: 14.w, + ), color: Colors.white, child: Row( mainAxisAlignment: MainAxisAlignment.center, @@ -101,19 +78,26 @@ class _ShareTrends extends State{ Expanded( child: Container( alignment: Alignment.center, - margin: EdgeInsets.only(left:60.w,), - child: Text( - "转发", - style: TextStyle( - color: Colors.black, - fontSize:17.sp, - fontWeight: MyFontWeight.regular, + margin: EdgeInsets.only( + left: 60.w, + ), + child: Text( + "转发", + style: TextStyle( + color: Colors.black, + fontSize: 17.sp, + fontWeight: MyFontWeight.regular, + ), ), - ),)), + ), + ), Container( - alignment: Alignment.center , - margin:EdgeInsets.only(right: 16.w) , - padding: EdgeInsets.symmetric(horizontal: 16.w,vertical: 3.h), + alignment: Alignment.center, + margin: EdgeInsets.only(right: 16.w), + padding: EdgeInsets.symmetric( + horizontal: 16.w, + vertical: 3.h, + ), decoration: BoxDecoration( color: Color(0xFF32A060), borderRadius: BorderRadius.circular(10.5), @@ -122,7 +106,7 @@ class _ShareTrends extends State{ S.of(context).fabu, style: TextStyle( color: Colors.white, - fontSize:12.sp, + fontSize: 12.sp, fontWeight: MyFontWeight.regular, ), ), @@ -130,12 +114,12 @@ class _ShareTrends extends State{ ], ), ), - Expanded(child: - Container( + Expanded( + child: Container( margin: EdgeInsets.symmetric(vertical: 14.h), width: double.infinity, color: Colors.white, - padding: EdgeInsets.only(left: 20.w,right: 16.w), + padding: EdgeInsets.only(left: 20.w, right: 16.w), child: Column( children: [ Container( @@ -145,15 +129,17 @@ class _ShareTrends extends State{ ), margin: EdgeInsets.only(top: 30.w), child: Container( - margin: EdgeInsets.only(left:16.w,right: 10.w,), + margin: EdgeInsets.only( + left: 16.w, + right: 10.w, + ), alignment: Alignment.topLeft, child: TextField( - textInputAction:TextInputAction.send, - onEditingComplete: () { - }, + textInputAction: TextInputAction.send, + onEditingComplete: () {}, maxLines: 8, minLines: 1, - focusNode:commentFocus, + focusNode: commentFocus, controller: textController, decoration: InputDecoration( border: InputBorder.none, @@ -167,60 +153,75 @@ class _ShareTrends extends State{ ), ), GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: (){ - Navigator.of(context).pushNamed( - '/router/scan_web', - arguments: { - "result": widget.arguments?["shareUrl"], - "title":"一心回乡", - }, - ); - }, - child: Container( - decoration: BoxDecoration( - color: Color(0xFFF2F2F2), - borderRadius: BorderRadius.circular(6), - ), - padding: EdgeInsets.only(top: 8.h,bottom: 8.h,left: 8.w,right: 10.w), - margin: EdgeInsets.only(top: 12.w), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if(article?.content != null && article!.content!.contains("images\":[\"") || (article?.coverImg ?? "")!= "") - MImage( - article?.content != null && - article!.content!.contains("images\":[\"") - ? jsonDecode(article!.content!)["images"][0] - : article?.coverImg ?? "", - radius: BorderRadius.circular(2), - fit: BoxFit.fill, - width: 64, - height: 64, - errorSrc: "assets/image/default_2_1.webp", - fadeSrc: "assets/image/default_2_1.webp", - ), - if(article?.content != null || article?.coverImg != null) - SizedBox(width: 7.w,), - Expanded(child: Text( - article?.mainTitle ?? "", - maxLines: 3, - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: Color(0xFF4D4D4D), - fontSize:14.sp, - height: 1.4.h, - fontWeight: MyFontWeight.regular, + behavior: HitTestBehavior.opaque, + onTap: () { + Navigator.of(context).pushNamed( + '/router/scan_web', + arguments: { + "result": widget.arguments?["shareUrl"], + "title": "一心回乡", + }, + ); + }, + child: Container( + decoration: BoxDecoration( + color: Color(0xFFF2F2F2), + borderRadius: BorderRadius.circular(6), + ), + padding: EdgeInsets.only( + top: 8.h, + bottom: 8.h, + left: 8.w, + right: 10.w, + ), + margin: EdgeInsets.only(top: 12.w), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (article?.content != null && + article!.content! + .contains("images\":[\"") || + (article?.coverImg ?? "") != "") + MImage( + article?.content != null && + article!.content! + .contains("images\":[\"") + ? jsonDecode(article!.content!)["images"][0] + : article?.coverImg ?? "", + radius: BorderRadius.circular(2), + fit: BoxFit.fill, + width: 64, + height: 64, + errorSrc: "assets/image/default_2_1.webp", + fadeSrc: "assets/image/default_2_1.webp", + ), + if (article?.content != null || + article?.coverImg != null) + SizedBox( + width: 7.w, + ), + Expanded( + child: Text( + article?.mainTitle ?? "", + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: Color(0xFF4D4D4D), + fontSize: 14.sp, + height: 1.4.h, + fontWeight: MyFontWeight.regular, + ), + ), ), - ),), - ], + ], + ), ), - )), + ), ], ), ), - ) + ), ], ), ), diff --git a/lib/constant.dart b/lib/constant.dart index f8b60273..6a38eb61 100644 --- a/lib/constant.dart +++ b/lib/constant.dart @@ -7,24 +7,26 @@ const String chatImageHost = "http://skk8mlm5b.hn-bkt.clouddn.com/"; /// socket的host和port端口 //47.93.216.24:9090 线上 192.168.10.200/192.168.10.129:9090 测试 -const String socketHost = kDebugMode ? '192.168.10.200' : '47.93.216.24'; +const String socketHost = kReleaseMode ? '192.168.10.200' : '47.93.216.24'; const int socketPort = 9090; const ipBaseUrl = "http://whois.pconline.com.cn"; /// 小程序接口的请求地址 -const localMiniBaseUrl = "http://192.168.10.54:8765/app/"; ///本地 +// const localMiniBaseUrl = "http://192.168.10.54:8765/app/"; ///本地 ///线上 /// app接口的请求地址 +const localMiniBaseUrl = "https://pos.api.yixinhuixiang.com/app/"; const serviceMiniBaseUrl = "https://pos.api.yixinhuixiang.com/app/"; ///线下 /// app接口的请求地址 -const localBaseUrl = "http://192.168.10.54:8766/app/"; ///本地 +// const localBaseUrl = "http://192.168.10.54:8766/app/"; ///本地 ///线上 +const localBaseUrl = "https://pos.platform.yixinhuixiang.com/app/"; const serviceBaseUrl = "https://pos.platform.yixinhuixiang.com/app/"; -///线上 +/// 线上 /// 对list进行分组 Map> groupBy(Iterable values, S Function(T) key) { var map = >{}; @@ -61,16 +63,16 @@ Map groupItem(Map> values, {int Function(T)? key}) { /// 最大值 T max(Iterable list, int Function(T) key) { - late T tt; + T? tt; for (T t in list) { if (tt == null) { tt = t; } - if (key(tt) < key(t)) { + if (key(tt!) < key(t)) { tt = t; } } - return tt; + return tt!; } extension ListExtension on Iterable { diff --git a/lib/data/article.dart b/lib/data/article.dart index cc6090d1..c1a1eefd 100644 --- a/lib/data/article.dart +++ b/lib/data/article.dart @@ -16,7 +16,7 @@ class Article { dynamic viceTitle; String? content = ''; String? coverImg = ''; - Author? author; + dynamic author; int? type = 0; int? likes = 0; int? viewers = 0; diff --git a/lib/data/article.g.dart b/lib/data/article.g.dart index 91a20059..7300039c 100644 --- a/lib/data/article.g.dart +++ b/lib/data/article.g.dart @@ -18,9 +18,7 @@ Article _$ArticleFromJson(Map json) => Article() ..viceTitle = json['viceTitle'] ..content = json['content'] as String? ..coverImg = json['coverImg'] as String? - ..author = json['author'] == null - ? null - : Author.fromJson(json['author'] as Map) + ..author = json['author'] ..type = (json['type'] as num?)?.toInt() ..likes = (json['likes'] as num?)?.toInt() ..viewers = (json['viewers'] as num?)?.toInt() @@ -53,7 +51,7 @@ Map _$ArticleToJson(Article instance) => { 'viceTitle': instance.viceTitle, 'content': instance.content, 'coverImg': instance.coverImg, - 'author': instance.author?.toJson(), + 'author': instance.author, 'type': instance.type, 'likes': instance.likes, 'viewers': instance.viewers, diff --git a/lib/data/vip_card.dart b/lib/data/vip_card.dart index 8824c11a..66f91830 100644 --- a/lib/data/vip_card.dart +++ b/lib/data/vip_card.dart @@ -1,3 +1,5 @@ +import 'dart:ui'; + import 'package:huixiang/data/store.dart'; import 'package:json_annotation/json_annotation.dart'; @@ -5,39 +7,69 @@ part 'vip_card.g.dart'; @JsonSerializable(explicitToJson: true) class VipCard { + @JsonKey() String? id = ''; + @JsonKey() String? createTime = ''; + @JsonKey() dynamic createUser; + @JsonKey() String? updateTime = ''; + @JsonKey() String? updateUser = ''; + @JsonKey() String? mid = ''; + @JsonKey() String? openid = ''; + @JsonKey() String? nickname = ''; + @JsonKey() String? headimg = ''; + @JsonKey() String? balance = ''; + @JsonKey() String? realRecharge = ''; + @JsonKey() String? sex = ''; + @JsonKey() bool? status = false; + @JsonKey() bool? onCredit = false; + @JsonKey() String? loginTime = ''; + @JsonKey() int? loginNum = 0; + @JsonKey() String? tenantCode = ''; + @JsonKey() int? source = 0; + @JsonKey() String? expendAmount = ''; + @JsonKey() int? buyTimes = 0; + @JsonKey() dynamic lastBuyTime; @JsonKey(name: "vip_no") dynamic vipNo; + @JsonKey() dynamic expireTime; + @JsonKey() int? integral = 0; + @JsonKey() int? level = 0; + @JsonKey() dynamic vipRegStore; + @JsonKey() String? tenantName = ''; + @JsonKey() String? tenantLogo = ''; + @JsonKey() List? storeList = []; VipCard(); + Color color = Color(0xFF32A060); + factory VipCard.fromJson(Map json) => _$VipCardFromJson(json); Map toJson() => _$VipCardToJson(this); diff --git a/lib/home/activity_list_page.dart b/lib/home/activity_list_page.dart index a21f318a..eb3d616b 100644 --- a/lib/home/activity_list_page.dart +++ b/lib/home/activity_list_page.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:keframe/keframe.dart'; @@ -39,9 +40,7 @@ class _ActivityListPage extends State List? activityList; queryActivity() async { - final SharedPreferences value = await SharedPreferences.getInstance(); - apiService = - ApiService(Dio(), context: context, token: value.getString('token')); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); BaseData>? baseData = await apiService?.informationList({ "pageNum": 1, "pageSize": 10, @@ -50,7 +49,7 @@ class _ActivityListPage extends State "state": 1 }).catchError((error) { _refreshController.refreshFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { _refreshController.refreshCompleted(); @@ -92,7 +91,7 @@ class _ActivityListPage extends State Navigator.of(context).pushNamed( '/router/web_page', arguments: { - "activityId": activityList![position].id + "activityId": activityList![position].id, }, ); }, diff --git a/lib/home/founder_story_page.dart b/lib/home/founder_story_page.dart index 6b7e970b..84d3fb79 100644 --- a/lib/home/founder_story_page.dart +++ b/lib/home/founder_story_page.dart @@ -33,7 +33,9 @@ class _FounderStoryPage extends State { children: [ Container( // margin: EdgeInsets.only(bottom: 20), - padding: EdgeInsets.only(left: 32.w, right: 32.w, top: 24.h), + padding: EdgeInsets.only( + left: 32.w, right: 32.w, top: 24.h, + ), decoration: BoxDecoration( color: Colors.white, boxShadow: [ @@ -41,7 +43,8 @@ class _FounderStoryPage extends State { color: Colors.black.withAlpha(12), offset: Offset(0, 2), blurRadius: 14, - spreadRadius: 0,) + spreadRadius: 0, + ), ], ), child: Column( @@ -55,9 +58,13 @@ class _FounderStoryPage extends State { SizedBox( height: 16, ), - Text("关于创始人", - style: TextStyle( - fontSize: 24.sp, color: Color(0xff565656))), + Text( + "关于创始人", + style: TextStyle( + fontSize: 24.sp, + color: Color(0xff565656), + ), + ), SizedBox( height: 18.h, ), @@ -75,8 +82,10 @@ class _FounderStoryPage extends State { color: Color(0xFF1A1A1A), fontSize: 12.sp, fontWeight: MyFontWeight.regular, - height: 1.5), - )), + height: 1.5, + ), + ), + ), Padding( padding: EdgeInsets.only(top: 50.h), child: Align( @@ -103,8 +112,10 @@ class _FounderStoryPage extends State { color: Color(0xFF1A1A1A), fontSize: 12.sp, fontWeight: MyFontWeight.regular, - height: 1.5.h), - )), + height: 1.5.h, + ), + ), + ), Image.asset( "assets/image/icon_story_2.webp", alignment: Alignment.centerRight, @@ -132,7 +143,9 @@ class _FounderStoryPage extends State { style: TextStyle( fontSize: 24.sp, fontWeight: MyFontWeight.regular, - color: Color(0xff565656))), + color: Color(0xff565656), + ), + ), SizedBox( height: 20, ), @@ -149,7 +162,9 @@ class _FounderStoryPage extends State { style: TextStyle( fontSize: 16.sp, fontWeight: MyFontWeight.regular, - color: Color(0xff565656))), + color: Color(0xff565656), + ), + ), ), _textWidget("2019年,在武汉成立湖北海峡姐妹餐饮有限公司。" "成为百年川椒火锅(光谷店)运营方,通过“素食煮义”和“蔬食之力”推广有机永续美好生活," @@ -169,7 +184,9 @@ class _FounderStoryPage extends State { style: TextStyle( fontSize: 24.sp, fontWeight: MyFontWeight.regular, - color: Color(0xff565656))), + color: Color(0xff565656), + ), + ), SizedBox( height: 26.h, ), @@ -205,7 +222,8 @@ class _FounderStoryPage extends State { color: Colors.black.withAlpha(12), offset: Offset(0, 2), blurRadius: 14, - spreadRadius: 0) + spreadRadius: 0, + ), ], ), child: RichText( @@ -217,8 +235,10 @@ class _FounderStoryPage extends State { color: Colors.white, fontSize: 12.sp, fontWeight: MyFontWeight.regular, - height: 1.5.h), - )), + height: 1.5.h, + ), + ), + ), ), Padding( padding: EdgeInsets.only( @@ -233,11 +253,14 @@ class _FounderStoryPage extends State { SizedBox( height: 27.h, ), - Text("传递理念", + Text( + "传递理念", style: TextStyle( fontSize: 24.sp, fontWeight: MyFontWeight.regular, - color: Color(0xff565656))), + color: Color(0xff565656), + ), + ), SizedBox( height: 20.h, ), @@ -264,108 +287,6 @@ class _FounderStoryPage extends State { ], ), ), - // Container( - // // margin: EdgeInsets.only(bottom: 20), - // // padding: EdgeInsets.all(16), - // decoration: BoxDecoration( - // color: Colors.white, - // boxShadow: [ - // BoxShadow( - // color: Colors.black.withAlpha(12), - // offset: Offset(0, 2), - // blurRadius: 14, - // spreadRadius: 0) - // ], - // ), - // child: Column( - // mainAxisAlignment: MainAxisAlignment.start, - // crossAxisAlignment: CrossAxisAlignment.start, - // children: [ - // Padding( - // padding: EdgeInsets.all(16), - // child: Text("评论 (58) 喜欢 (58)", - // style: TextStyle( - // fontSize: 16, - // fontWeight: FontWeight.bold, - // color: Color(0xff1A1A1A))), - // ), - // SizedBox( - // height: 600, - // child: ListView.builder( - // itemCount: 6, - // scrollDirection: Axis.vertical, - // physics: BouncingScrollPhysics(), - // itemBuilder: (context, position) { - // return _commentItem(position); - // }, - // ), - // ), - // ], - // ), - // ), - // SizedBox( - // height: 12, - // ), - // Container( - // padding: EdgeInsets.all(16), - // decoration: BoxDecoration( - // color: Colors.white, - // boxShadow: [ - // BoxShadow( - // color: Colors.black.withAlpha(12), - // offset: Offset(0, 2), - // blurRadius: 14, - // spreadRadius: 0) - // ], - // borderRadius: new BorderRadius.only( - // topLeft: Radius.circular(8.0), - // topRight: Radius.circular(8.0), - // ), - // ), - // child: Row( - // children: [ - // Expanded( - // flex: 1, - // child: Container( - // decoration: new BoxDecoration( - // color: Color(0xffF2F2F2), - // borderRadius: BorderRadius.circular(2.0)), - // child: Column( - // children: [ - // Container( - // margin: const EdgeInsets.fromLTRB(4, 0, 4, 0), - // alignment: Alignment.topLeft, - // child: TextField( - // maxLines: 8, - // minLines: 1, - // decoration: InputDecoration( - // border: InputBorder.none, - // hintText: "留下您精彩的评论吧~", - // hintStyle: TextStyle( - // fontSize: 14, - // color: Color(0xffCDCCCC), - // ), - // ), - // ), - // ), - // ], - // ), - // ), - // ), - // Padding( - // padding: EdgeInsets.only(left: 20, right: 20), - // child: Text( - // "发送", - // style: TextStyle( - // fontSize: 16, - // fontWeight: FontWeight.bold, - // color: Color(0XFF1A1A1A)), - // ), - // ), - // Image.asset("assets/image/icon_like_h.webp") - // ], - // ), - // ), ], ), ), @@ -382,7 +303,10 @@ class _FounderStoryPage extends State { children: [ Text( "●", - style: TextStyle(fontSize: 10.sp, color: Color(0xff32A060)), + style: TextStyle( + fontSize: 10.sp, + color: Color(0xff32A060), + ), ), SizedBox( width: 5.w, @@ -392,7 +316,10 @@ class _FounderStoryPage extends State { style: TextStyle( fontSize: 12.sp, fontWeight: MyFontWeight.regular, - color: Colors.black))), + color: Colors.black, + ), + ), + ), ], ), ); @@ -421,23 +348,11 @@ class _FounderStoryPage extends State { style: TextStyle( fontSize: 18.sp, fontWeight: MyFontWeight.light, - color: Colors.white), - ) + color: Colors.white, + ), + ), ], ), - // CircleAvatar( - // radius: 100, - // backgroundImage: Image.asset(img), - // child: Container( - // alignment: Alignment.center, - // child: Text( - // text, - // style: TextStyle( - // fontSize: 18, - // fontWeight: FontWeight.w300, - // color: Colors.white), - // )), - // ), ), Container( width: 73.w, @@ -446,136 +361,13 @@ class _FounderStoryPage extends State { painter: MyPainter( lineColor: Color(0xff32A060), width: 2.w, - isDividerRound: true), + isDividerRound: true, + ), ), - ) + ), ], ), ); } -// Widget _commentItem(var position) { -// return Container( -// child: Column( -// children: [ -// Padding( -// padding: EdgeInsets.all(16), -// child: Row( -// mainAxisAlignment: MainAxisAlignment.spaceBetween, -// crossAxisAlignment: CrossAxisAlignment.center, -// children: [ -// ClipOval( -// child: Image.network( -// "https://t7.baidu.com/it/u=2841334870,333581502&fm=193&f=GIF", -// fit: BoxFit.cover, -// width: 40, -// height: 40, -// ), -// clipBehavior: Clip.hardEdge, -// ), -// SizedBox( -// width: 12, -// ), -// Expanded( -// child: Container( -// height: 60, -// child: Column( -// mainAxisAlignment: MainAxisAlignment.spaceEvenly, -// crossAxisAlignment: CrossAxisAlignment.start, -// children: [ -// Text.rich( -// TextSpan(children: [ -// TextSpan( -// text: "张三", -// style: TextStyle( -// fontWeight: FontWeight.bold, -// fontSize: 14, -// color: Colors.black), -// ), -// ]), -// textDirection: TextDirection.ltr, -// ), -// Text( -// "2021.04.12 12:12", -// overflow: TextOverflow.ellipsis, -// maxLines: 2, -// style: TextStyle( -// fontSize: 12, -// color: Color(0xff808080), -// ), -// ), -// ], -// ), -// ), -// flex: 1, -// ), -// Container( -// alignment: Alignment.topRight, -// child: Row( -// children: [ -// Image.asset( -// "assets/image/icon_like.webp", -// width: 16, -// height: 16, -// ), -// Text( -// "58", -// style: -// TextStyle(fontSize: 12, color: Color(0xff1A1A1A)), -// ), -// ], -// ), -// ), -// ], -// ), -// ), -// Padding( -// padding: EdgeInsets.only(left: 68, right: 16), -// child: Text( -// "文本,是指书面语言的表现形式,从文学角度说,通常是具有完整、系统含义(Mess…", -// style: TextStyle(fontSize: 14, color: Color(0xff1A1A1A)), -// ), -// ), -// SizedBox( -// height: 12, -// ), -// Container( -// width: double.infinity, -// margin: EdgeInsets.only(left: 68, right: 16), -// decoration: new BoxDecoration( -// color: Color(0xffF2F2F2), -// borderRadius: BorderRadius.circular(2.0), -// ), -// child: Padding( -// padding: EdgeInsets.only(left: 4, top: 4, bottom: 4), -// child: Text( -// "文本,是指书面语言的表现形式文本,是指、", -// style: TextStyle(fontSize: 12, color: Color(0xff808080)), -// ), -// ), -// ), -// if (position == 5) -// Container( -// height: 63, -// decoration: BoxDecoration( -// color: Color(0xffF2F2F2), -// boxShadow: [ -// BoxShadow( -// color: Colors.black.withAlpha(12), -// offset: Offset(0, 2), -// blurRadius: 14, -// spreadRadius: 0) -// ], -// ), -// margin: EdgeInsets.only(top: 30), -// alignment: Alignment.center, -// child: Text( -// "-已显示全部评论-", -// style: TextStyle(fontSize: 14, color: Color(0xff353535)), -// ), -// ), -// ], -// ), -// ); -// } } diff --git a/lib/home/guide_page.dart b/lib/home/guide_page.dart index db6742e7..b24ad163 100644 --- a/lib/home/guide_page.dart +++ b/lib/home/guide_page.dart @@ -6,6 +6,7 @@ import 'package:flutter/material.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/constant.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/round_button.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -27,24 +28,9 @@ class _GuidePage extends State { } isLogin() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - - if (sharedPreferences.getBool("isShowPrivacyPolicy") == null || - !(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) { + if (!SharedInstance.instance.isShowPrivacyPolicy) { showAlertDialog(); } - - // if (sharedPreferences.containsKey('token') && - // sharedPreferences.getString("token") != null && - // sharedPreferences.getString("token") != "") { - // Navigator.of(context).popAndPushNamed('/router/main_page'); - // } else { - // initController(); - // - // apiService = ApiService(Dio(), context: context); - // isShowLogin = true; - // setState(() {}); - // } } @override @@ -70,7 +56,9 @@ class _GuidePage extends State { color: Colors.white, child: Center( child: Container( - margin: EdgeInsets.only(top: 120.h, left: 19.w, right: 19.w), + margin: EdgeInsets.only( + top: 120.h, left: 19.w, right: 19.w, + ), child: Stack( children: [ Column( @@ -164,7 +152,9 @@ class _GuidePage extends State { color: Colors.white, child: Center( child: Container( - margin: EdgeInsets.only(top: 120.h, left: 19.w, right: 19.w), + margin: EdgeInsets.only( + top: 120.h, left: 19.w, right: 19.w, + ), child: Stack( children: [ Column( @@ -478,7 +468,8 @@ class _GuidePage extends State { child: Column( children: [ Text.rich( - TextSpan(children: [ + TextSpan( + children: [ TextSpan( text: S.of(context).yinsizhengce1, style: TextStyle( @@ -497,11 +488,11 @@ class _GuidePage extends State { ), recognizer: TapGestureRecognizer() ..onTap = () { - Navigator.of(context) - .popAndPushNamed('/router/treaty_page'); + Navigator.of(context).popAndPushNamed('/router/treaty_page'); }, ), - ]), + ], + ), ), 10.d, Text( @@ -557,9 +548,7 @@ class _GuidePage extends State { textColor: Colors.white, fontSize: 12.sp, callback: () { - SharedPreferences.getInstance().then((value) { - value.setBool("isShowPrivacyPolicy", true); - }); + SharedInstance.instance.showPrivacyPolicy(); SharesdkPlugin.uploadPrivacyPermissionStatus( 1, (success) { @@ -591,14 +580,12 @@ class _GuidePage extends State { } toNext() { - SharedPreferences.getInstance().then((value) { - value.setBool("isFirst", false); - String? token = value.getString("token"); - if (token?.isEmpty ?? true) { - Navigator.of(context).popAndPushNamed('/router/new_login_page'); - } else { - Navigator.of(context).popAndPushNamed('/router/main_page'); - } - }); + SharedInstance.instance.setFirst(); + String token = SharedInstance.instance.token; + if (token.isEmpty) { + Navigator.of(context).popAndPushNamed('/router/new_login_page'); + } else { + Navigator.of(context).popAndPushNamed('/router/main_page'); + } } } diff --git a/lib/home/help_farmers/help_farmers_page.dart b/lib/home/help_farmers/help_farmers_page.dart index e1d24255..a76f6e48 100644 --- a/lib/home/help_farmers/help_farmers_page.dart +++ b/lib/home/help_farmers/help_farmers_page.dart @@ -9,6 +9,7 @@ import 'package:huixiang/data/good_list.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/home/help_farmers/farmers_tab.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shimmer/shimmer.dart'; @@ -38,20 +39,18 @@ class _HelpFarmersPage extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, - token: value.getString('token'), - showLoading: true), - queryConfig(), - }); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: true, + ); + queryConfig(); } ///助农列表 queryConfig() async { try { - BaseListData? baseData = - await apiService?.getConfig().catchError((error) { + BaseListData? baseData = await apiService?.getConfig().catchError((error) { networkStatus = -1; refreshController.refreshFailed(); return BaseListData()..isSuccess = false; @@ -224,7 +223,9 @@ class _HelpFarmersPage extends State { isShowBtn: false, text: "当前分类暂无商品", fontSize: 16.sp, - margin: EdgeInsets.only(top: 120.h, left: 60.w, right: 60.w), + margin: EdgeInsets.only( + top: 120.h, left: 60.w, right: 60.w, + ), ) : StaggeredGrid.count( crossAxisCount: 2, @@ -260,7 +261,7 @@ class _HelpFarmersPage extends State { offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, - ) + ), ], color: Colors.white, ), @@ -298,12 +299,13 @@ class _HelpFarmersPage extends State { ), ), Padding( - padding: EdgeInsets.only(left: 10.w, bottom: 12.h), + padding: EdgeInsets.only( + left: 10.w, bottom: 12.h, + ), child: Row( children: [ Text( - AppUtils.calculateDouble( - double.tryParse("${goodList.price}") ?? 0), + AppUtils.calculateDouble(double.tryParse("${goodList.price}") ?? 0), style: TextStyle( fontSize: 24.sp, fontFamily: 'APPHT', @@ -313,7 +315,9 @@ class _HelpFarmersPage extends State { ), Container( margin: EdgeInsets.only(left: 8.w), - padding: EdgeInsets.symmetric(vertical: 3.h, horizontal: 9.w), + padding: EdgeInsets.symmetric( + vertical: 3.h, horizontal: 9.w, + ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(100), boxShadow: [ @@ -355,8 +359,9 @@ class _HelpFarmersPage extends State { offset: Offset(0, 1), blurRadius: 12, spreadRadius: 0, - ) - ]), + ), + ], + ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -372,7 +377,9 @@ class _HelpFarmersPage extends State { Row( children: [ Padding( - padding: EdgeInsets.only(left: 6.w, bottom: 5.h, top: 12.h), + padding: EdgeInsets.only( + left: 6.w, bottom: 5.h, top: 12.h, + ), child: Shimmer.fromColors( baseColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8), @@ -387,7 +394,9 @@ class _HelpFarmersPage extends State { ), ), Padding( - padding: EdgeInsets.only(left: 12.w, bottom: 5.h, top: 12.h), + padding: EdgeInsets.only( + left: 12.w, bottom: 5.h, top: 12.h, + ), child: Shimmer.fromColors( baseColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8), @@ -402,7 +411,9 @@ class _HelpFarmersPage extends State { ), ), Padding( - padding: EdgeInsets.only(left: 12.w, bottom: 5.h, top: 12.h), + padding: EdgeInsets.only( + left: 12.w, bottom: 5.h, top: 12.h, + ), child: Shimmer.fromColors( baseColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8), @@ -417,7 +428,9 @@ class _HelpFarmersPage extends State { ), ), Padding( - padding: EdgeInsets.only(left: 12.w, bottom: 5.h, top: 12.h), + padding: EdgeInsets.only( + left: 12.w, bottom: 5.h, top: 12.h, + ), child: Shimmer.fromColors( baseColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8), @@ -457,8 +470,9 @@ class _HelpFarmersPage extends State { ), ), Padding( - padding: - EdgeInsets.only(top: 7.h, left: 10.w, bottom: 8.h), + padding: EdgeInsets.only( + top: 7.h, left: 10.w, bottom: 8.h, + ), child: Shimmer.fromColors( baseColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8), @@ -509,7 +523,8 @@ class _HelpFarmersPage extends State { ), ); }, - )), + ), + ), ], ), ); diff --git a/lib/home/home_page.dart b/lib/home/home_page.dart index 5f5d56ef..13373713 100644 --- a/lib/home/home_page.dart +++ b/lib/home/home_page.dart @@ -6,8 +6,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:flutter_swiper_view/flutter_swiper_view.dart'; -import 'package:get/get.dart'; -import 'package:get/utils.dart'; import 'package:huixiang/data/activity_pos.dart'; import 'package:huixiang/data/article.dart'; import 'package:huixiang/data/banner.dart'; @@ -20,6 +18,7 @@ import 'package:huixiang/data/goods_category.dart'; import 'package:huixiang/data/home_rank.dart'; import 'package:huixiang/data/login_info.dart'; import 'package:huixiang/data/page.dart'; +import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/home/home_view/discount_zone.dart'; import 'package:huixiang/home/home_view/home_recommend_goods.dart'; @@ -31,19 +30,18 @@ import 'package:huixiang/home/points_mall_view/points_goods_view.dart'; import 'package:huixiang/main.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; +import 'package:huixiang/utils/flutter_utils.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/activity_coupons.dart'; import 'package:huixiang/view_widget/activity_poster.dart'; +import 'package:huixiang/view_widget/channel_dialog.dart'; import 'package:huixiang/view_widget/classic_header.dart'; +import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/invite_success_dialog.dart'; import 'package:huixiang/view_widget/request_permission.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import '../data/user_info.dart'; -import '../utils/flutter_utils.dart'; -import '../view_widget/channel_dialog.dart'; -import '../view_widget/custom_image.dart'; import 'home_view/happy_help_farmers.dart'; import 'home_view/shortcut_operation.dart'; @@ -99,29 +97,20 @@ class HomePageState extends State with AutomaticKeepAliveClientMixin { setState(() {}); } }); - if (apiService == null) { - SharedPreferences.getInstance().then((value) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - _onRefresh(isFirstIn: true); - }); - } + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + _onRefresh(isFirstIn: true); if (showInvite) { inviteShowAlertDialog(widget.invite, widget.interviewCouponList?[0]); showInvite = false; } - if ((widget.invite?.isNotEmpty ?? false) || - (widget.interviewCouponList?.isNotEmpty ?? false)) { + if ((widget.invite?.isNotEmpty ?? false) || (widget.interviewCouponList?.isNotEmpty ?? false)) { showInvite = true; } - - //判断新人弹窗 - // if (widget.firstLoginCouponList != null && widget.firstLoginCouponList.length > 0) - // showNew = true; } ///邀请成功 @@ -138,22 +127,18 @@ class HomePageState extends State with AutomaticKeepAliveClientMixin { ///活动海报弹窗 posterShowAlertDialog(ActivityPos? activityPos, firstLoginCouponList) { var today = DateTime.now().day; - SharedPreferences.getInstance().then((value) { - if (value.getInt("today") == today && - (value.getString("ActivityPosCode") ?? "") - .contains("${activityPos?.code}_${value.getString("userId")};")) - return; - value.setString("ActivityPosCode", - "${(value.getString("ActivityPosCode") ?? "")}${activityPos?.code}_${value.getString("userId")};"); - value.setInt("today", today); - //显示对话框 - showDialog( - context: context, - builder: (BuildContext context) { - return ActivityPoster(activityPos, firstLoginCouponList); - }, - ); - }); + + if (SharedInstance.instance.today == today && (SharedInstance.instance.ActivityPosCode).contains("${activityPos?.code}_${SharedInstance.instance.userId};")) + return; + SharedInstance.instance.saveActivityPosCode("${SharedInstance.instance.ActivityPosCode}${activityPos?.code}_${SharedInstance.instance.userId};"); + SharedInstance.instance.saveToday(today); + //显示对话框 + showDialog( + context: context, + builder: (BuildContext context) { + return ActivityPoster(activityPos, firstLoginCouponList); + }, + ); } ///推荐渠道弹窗 @@ -309,7 +294,7 @@ class HomePageState extends State with AutomaticKeepAliveClientMixin { // apiService = ApiService( // Dio(), // context: context, -// token: value.getString("token"), +// token: SharedInstance.instance.token, // ); // } // BaseData>? baseData = await apiService?.stats().catchError((onError) {}); @@ -337,22 +322,16 @@ class HomePageState extends State with AutomaticKeepAliveClientMixin { ///核销用户优惠券 queryWiped(memberCouponId) async { - if (apiService == null) { - SharedPreferences.getInstance().then((value) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - }); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); BaseData? baseData = await apiService?.wiped(memberCouponId).catchError((onError) { return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { SmartDialog.showToast("核销成功", alignment: Alignment.center); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -556,18 +535,26 @@ class HomePageState extends State with AutomaticKeepAliveClientMixin { bannerClick(BannerData bannerData) async { switch (bannerData.contentType) { case 1: - Navigator.of(context).pushNamed('/router/integral_store_page', - arguments: {"goodsId": bannerData.content}); + Navigator.of(context).pushNamed( + '/router/integral_store_page', + arguments: { + "goodsId": bannerData.content, + }, + ); break; case 2: - Navigator.of(context).pushNamed('/router/web_page', arguments: { - "activityId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', arguments: { + "activityId": bannerData.content, + }, + ); break; case 3: - Navigator.of(context).pushNamed('/router/web_page', arguments: { - "articleId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', arguments: { + "articleId": bannerData.content, + }, + ); break; case 4: String? router = bannerData.content; @@ -599,7 +586,8 @@ class HomePageState extends State with AutomaticKeepAliveClientMixin { Map map = jsonDecode(params); Navigator.of(context).pushNamed( router.substring(0, router.indexOf("?")), - arguments: map); + arguments: map, + ); break; } } diff --git a/lib/home/home_view/activity_list.dart b/lib/home/home_view/activity_list.dart index fb95ea36..850c6402 100644 --- a/lib/home/home_view/activity_list.dart +++ b/lib/home/home_view/activity_list.dart @@ -8,6 +8,7 @@ import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -41,8 +42,7 @@ class _ActivityList extends State List? activityList; queryActivity() async { - final SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService(Dio(), context: context, token: value.getString('token')); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); BaseData>? baseData = await apiService?.informationList({ "pageNum": 1, "pageSize": 10, @@ -51,7 +51,7 @@ class _ActivityList extends State "state": 1 }).catchError((error) { _refreshController.refreshFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { _refreshController.refreshCompleted(); diff --git a/lib/home/home_view/brand_view.dart b/lib/home/home_view/brand_view.dart index 9d89e782..1d2d2b09 100644 --- a/lib/home/home_view/brand_view.dart +++ b/lib/home/home_view/brand_view.dart @@ -72,7 +72,7 @@ class _BrandView extends State { ), ); }, - itemCount: widget.brandData.length ?? 0, + itemCount: widget.brandData.length, ), ); } diff --git a/lib/home/home_view/coupon.dart b/lib/home/home_view/coupon.dart index 212022e6..820f7acc 100644 --- a/lib/home/home_view/coupon.dart +++ b/lib/home/home_view/coupon.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/coupon.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/item_title.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/view_widget/receive_success.dart'; @@ -29,15 +30,12 @@ class _CouponView extends State { @override void initState() { super.initState(); - - SharedPreferences.getInstance().then((value) => { - apiService = ApiService( - Dio(), - context: context, - token: value.getString('token'), - ), - queryCoupon(), - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + queryCoupon(); } queryCoupon() async { @@ -48,7 +46,7 @@ class _CouponView extends State { "searchKey": "", "state": 0 }).catchError((onError) { - return Future.value(null); + return BaseData>()..isSuccess = false; }); coupons.clear(); if (baseData?.isSuccess ?? false) { @@ -78,7 +76,7 @@ class _CouponView extends State { itemBuilder: (context, position) { return couponItem(coupons[position]); }, - itemCount:coupons == null ? 0 : coupons.length, + itemCount: coupons.length, ), ), ], @@ -177,8 +175,8 @@ class _CouponView extends State { Expanded( child: Container( margin: EdgeInsets.symmetric( - vertical: 10.h, horizontal: 15.w, - ), + vertical: 10.h, horizontal: 15.w, + ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, @@ -271,7 +269,8 @@ class _CouponView extends State { receiveCoupon(couponId) async { BaseData? baseData = await apiService?.receiveCoupon(couponId).catchError((onError) { - return Future.value(null);}); + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { queryCoupon(); showAlertDialog(); diff --git a/lib/home/home_view/discount_zone.dart b/lib/home/home_view/discount_zone.dart index 3864bb8c..f1b41c43 100644 --- a/lib/home/home_view/discount_zone.dart +++ b/lib/home/home_view/discount_zone.dart @@ -18,7 +18,6 @@ class DiscountZone extends StatefulWidget { } class _DiscountZone extends State { - ApiService? apiService; @override void initState() { diff --git a/lib/home/home_view/featured_acticvity.dart b/lib/home/home_view/featured_acticvity.dart index 10a5f3dc..0af59dca 100644 --- a/lib/home/home_view/featured_acticvity.dart +++ b/lib/home/home_view/featured_acticvity.dart @@ -6,6 +6,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/item_title.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -29,8 +30,7 @@ class _FeaturedActivity extends State { List? activityList; queryActivity() async { - final SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService(Dio(), context: context, token: value.getString('token')); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); BaseData>? baseData = await apiService?.informationList({ "pageNum": 1, "pageSize": 10, @@ -38,7 +38,8 @@ class _FeaturedActivity extends State { "type": 1, "state": 1 }).catchError((error) { - return Future.value(null);}); + return BaseData>()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { activityList = baseData?.data?.list ?? []; if (activityList!.length == 1) @@ -70,8 +71,10 @@ class _FeaturedActivity extends State { if (activityList?.isNotEmpty ?? false) GestureDetector( onTap: () { - Navigator.of(context).pushNamed('/router/web_page', - arguments: {"activityId": activityList?[0].id}); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: {"activityId": activityList?[0].id}, + ); }, child: Container( child: stackItem(18.sp, activityList?[0]), @@ -98,8 +101,10 @@ class _FeaturedActivity extends State { children: [ GestureDetector( onTap: () { - Navigator.of(context).pushNamed('/router/web_page', - arguments: {"activityId": activityList?[1].id}); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: {"activityId": activityList?[1].id}, + ); }, child: Container( child: stackItem(12.sp, activityList?[1]), @@ -118,31 +123,6 @@ class _FeaturedActivity extends State { ), ), ), - // SizedBox( - // height: 5, - // ), - // GestureDetector( - // onTap: () { - // Navigator.of(context).pushNamed('/router/web_page', - // arguments: {"activityId": activityList[2].id}); - // }, - // child: Container( - // child: stackItem(12.sp, activityList[2]), - // margin: EdgeInsets.symmetric(horizontal: 5.w), - // width: (MediaQuery.of(context).size.width - 42) / 2, - // height: 190.h / 2, - // decoration: BoxDecoration( - // borderRadius: BorderRadius.circular(4), - // color: Colors.blue, - // image: DecorationImage( - // image: NetworkImage( - // activityList[2].coverImg, - // ), - // fit: BoxFit.fill, - // ), - // ), - // ), - // ), ], ), ), @@ -232,8 +212,9 @@ class _FeaturedActivity extends State { ), Spacer() ], - ) + ), ], - )); + ), + ); } } diff --git a/lib/home/home_view/founder_store.dart b/lib/home/home_view/founder_store.dart index 28891dc8..5d5e812e 100644 --- a/lib/home/home_view/founder_store.dart +++ b/lib/home/home_view/founder_store.dart @@ -32,8 +32,7 @@ class _FounderStore extends State { ), GestureDetector( onTap: () { - Navigator.of(context) - .pushNamed('/router/founder_story_page'); + Navigator.of(context).pushNamed('/router/founder_story_page'); }, child: founderStore(), ), @@ -44,7 +43,9 @@ class _FounderStore extends State { Widget founderStore() { return Container( - margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 22.h, bottom: 28.h), + margin: EdgeInsets.only( + left: 16.w, right: 16.w, top: 22.h, bottom: 28.h, + ), decoration: BoxDecoration( boxShadow: [ BoxShadow( diff --git a/lib/home/home_view/happy_help_farmers.dart b/lib/home/home_view/happy_help_farmers.dart index 40777c95..2de53cc2 100644 --- a/lib/home/home_view/happy_help_farmers.dart +++ b/lib/home/home_view/happy_help_farmers.dart @@ -13,14 +13,12 @@ class HappyHelpFarmers extends StatefulWidget { } class _HappyHelpFarmers extends State { - ApiService? apiService; @override void initState() { super.initState(); } - @override Widget build(BuildContext context) { return Container( diff --git a/lib/home/home_view/home_banner.dart b/lib/home/home_view/home_banner.dart index 970e017a..da895648 100644 --- a/lib/home/home_view/home_banner.dart +++ b/lib/home/home_view/home_banner.dart @@ -75,18 +75,26 @@ class _HomeBanner extends State { bannerClick(BannerData bannerData) async { switch (bannerData.contentType) { case 1: - Navigator.of(context).pushNamed('/router/integral_store_page', - arguments: {"goodsId": bannerData.content}); + Navigator.of(context).pushNamed( + '/router/integral_store_page', + arguments: {"goodsId": bannerData.content}, + ); break; case 2: - Navigator.of(context).pushNamed('/router/web_page', arguments: { - "activityId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "activityId": bannerData.content, + }, + ); break; case 3: - Navigator.of(context).pushNamed('/router/web_page', arguments: { - "articleId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "articleId": bannerData.content, + }, + ); break; case 4: String? router = bannerData.content; @@ -105,9 +113,12 @@ class _HomeBanner extends State { } break; case 5: - Navigator.of(context).pushNamed('/router/class_details', arguments: { - "id": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/class_details', + arguments: { + "id": bannerData.content, + }, + ); break; case 7: String? router = bannerData.content; diff --git a/lib/home/home_view/home_integral_store.dart b/lib/home/home_view/home_integral_store.dart index acd4ec40..ba763edb 100644 --- a/lib/home/home_view/home_integral_store.dart +++ b/lib/home/home_view/home_integral_store.dart @@ -45,7 +45,9 @@ class _HomeIntegralStore extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Padding(padding: EdgeInsets.only(left: 16,bottom: 10),child: Text( + Padding( + padding: EdgeInsets.only(left: 16,bottom: 10), + child: Text( S.of(context).dajiadouzaiduihuan, textAlign: TextAlign.end, style: TextStyle( @@ -85,8 +87,10 @@ class _HomeIntegralStore extends State { itemBuilder: (context, index) { return GestureDetector( onTap: () { - Navigator.of(context).pushNamed('/router/integral_store_page', - arguments: {"goodsId": widget.gooods[index].id}); + Navigator.of(context).pushNamed( + '/router/integral_store_page', + arguments: {"goodsId": widget.gooods[index].id}, + ); }, child: buildItem(widget.gooods[index]), ); diff --git a/lib/home/home_view/home_recommend_goods.dart b/lib/home/home_view/home_recommend_goods.dart index 3b5e6bde..7f3bc417 100644 --- a/lib/home/home_view/home_recommend_goods.dart +++ b/lib/home/home_view/home_recommend_goods.dart @@ -1,8 +1,10 @@ +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:huixiang/data/home_rank.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/flutter_utils.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:huixiang/utils/font_weight.dart'; @@ -25,6 +27,11 @@ class _HomeRecommendGoods extends State { @override void initState() { + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); super.initState(); } @@ -145,4 +152,5 @@ class _HomeRecommendGoods extends State { ), ); } + } diff --git a/lib/home/home_view/hot_article.dart b/lib/home/home_view/hot_article.dart index ffd73ad4..35119750 100644 --- a/lib/home/home_view/hot_article.dart +++ b/lib/home/home_view/hot_article.dart @@ -29,8 +29,7 @@ class _HotArticle extends State { imgPath: "assets/image/icon_today_video.webp", moreText: S.of(context).chakangengduo, onTap: () { - Navigator.of(context) - .pushNamed('/router/hot_article_page'); + Navigator.of(context).pushNamed('/router/hot_article_page'); }, ), hotList(), @@ -43,9 +42,7 @@ class _HotArticle extends State { return Container( child: ListView.builder( shrinkWrap: true, - itemCount: widget.articles != null - ? ((widget.articles.length > 3) ? 3 : widget.articles.length) - : 0, + itemCount: ((widget.articles.length > 3) ? 3 : widget.articles.length), physics: NeverScrollableScrollPhysics(), scrollDirection: Axis.vertical, padding: EdgeInsets.symmetric(vertical: 12.h), @@ -56,7 +53,9 @@ class _HotArticle extends State { height: position == 0 ? 247.h : 96.h, margin: EdgeInsets.symmetric(vertical: 6.h, horizontal: 16.w), child: HotArticleItem( - article: widget.articles[position], isHot: position == 0), + article: widget.articles[position], + isHot: position == 0, + ), ), ); }, diff --git a/lib/home/home_view/quick_order.dart b/lib/home/home_view/quick_order.dart index 0d23f6ec..a412c159 100644 --- a/lib/home/home_view/quick_order.dart +++ b/lib/home/home_view/quick_order.dart @@ -10,6 +10,7 @@ import 'package:huixiang/utils/location.dart'; import 'package:huixiang/data/store.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/item_title.dart'; @@ -36,6 +37,10 @@ class _QuickOrder extends State { @override void initState() { + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); super.initState(); getLatLng(); startLocation(); @@ -60,44 +65,30 @@ class _QuickOrder extends State { } getLatLng() async { - SharedPreferences.getInstance().then( - (value) => { - apiService = ApiService(Dio(), - context: context, - token: value.getString('token'), - showLoading: false), - if (value.containsKey("latitude") && - value.containsKey("longitude") ) - { - latLng = Position( - latitude: double.tryParse(value.getString("latitude") ??"")!, - longitude: double.tryParse(value.getString("longitude") ?? "")!, - timestamp: DateTime.now(), - accuracy: 0, - altitude: 0, - heading: 0, - speed: 0, - speedAccuracy: 0 - ), - queryStore( - value.getString("latitude"), - value.getString("longitude"), - editingController.text, - ), - setState(() { - // _mapController?.updateMapOptions( - // BMFMapOptions( - // center: latLng, - // zoomLevel: 15, - // )); - }) - } - else - { - queryStore("", "", editingController.text), - } - }, - ); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); + if (SharedInstance.instance.latitude.isNotEmpty && SharedInstance.instance.longitude.isNotEmpty) { + latLng = Position( + latitude: double.tryParse(SharedInstance.instance.latitude)!, + longitude: double.tryParse(SharedInstance.instance.longitude)!, + timestamp: DateTime.now(), + accuracy: 0, + altitude: 0, + heading: 0, + speed: 0, + speedAccuracy: 0 + ); + queryStore( + SharedInstance.instance.latitude, + SharedInstance.instance.longitude, + editingController.text, + ); + setState(() {}); + } else { + queryStore("", "", editingController.text); + } } startLocation() async { @@ -125,11 +116,6 @@ class _QuickOrder extends State { "${latLng?.latitude}", "${latLng?.longitude}", editingController.text); - // _mapController?.updateMapOptions(BMFMapOptions( - // center: value, - // zoomLevel: 15, - // ) - // ); return r; }); } @@ -137,12 +123,10 @@ class _QuickOrder extends State { } saveLatLng(Position latLng, province, city, district) async { - SharedPreferences prefs = await SharedPreferences.getInstance(); - await prefs.setString("latitude", "${latLng.latitude}"); - await prefs.setString("longitude", "${latLng.longitude}"); - if (province != null) await prefs.setString("province", province); - if (city != null) await prefs.setString("city", city); - if (district != null) await prefs.setString("district", district); + SharedInstance.instance.saveLatLng(latLng); + if (province != null) SharedInstance.instance.setProvince(province); + if (city != null) SharedInstance.instance.setCity(city); + if (district != null) SharedInstance.instance.setDistrict(district); } @override @@ -267,14 +251,6 @@ class _QuickOrder extends State { ), ), ), - // Text( - // store?.remark ??"", - // style: TextStyle( - // fontSize: 10.sp, - // fontWeight: MyFontWeight.medium, - // color: Color(0xFF868686), - // ), - // ), SizedBox( height: 5, ), @@ -386,7 +362,7 @@ class _QuickOrder extends State { // 新版桌子码跳转 // http://miniscan.lotus-wallet.com/placeorder?tenant_code=1194&table_id=1669609340031467520&store_id=1637659387134738432 var result = await Navigator.of(context).pushNamed('/router/qr_scan'); - if (result == null || result !is String || (result as String).isEmpty) { + if (result == null || result is String || (result as String).isEmpty) { return; } // String result = await scanner.scan(); @@ -394,9 +370,7 @@ class _QuickOrder extends State { String tableId = uri.queryParameters["tableId"] ?? uri.queryParameters["table_id"] ?? ""; String tenantCode = uri.queryParameters["tenantCode"] ?? uri.queryParameters["tenant_code"] ?? ""; String shopId = uri.queryParameters["shopId"] ?? uri.queryParameters["store_id"] ?? ""; - if (tableId != "" && - tenantCode != "" && - shopId != "") { + if (tableId != "" && tenantCode != "" && shopId != "") { Navigator.of(context).pushNamed( '/router/store_order', arguments: { diff --git a/lib/home/home_view/shortcut_operation.dart b/lib/home/home_view/shortcut_operation.dart index 7e8ca613..1712d247 100644 --- a/lib/home/home_view/shortcut_operation.dart +++ b/lib/home/home_view/shortcut_operation.dart @@ -16,7 +16,6 @@ class ShortcutOperation extends StatefulWidget { } class _ShortcutOperation extends State { - ApiService? apiService; @override void initState() { diff --git a/lib/home/home_view/sign_view.dart b/lib/home/home_view/sign_view.dart index 99dae84a..ce93f31f 100644 --- a/lib/home/home_view/sign_view.dart +++ b/lib/home/home_view/sign_view.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/item_title.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -27,29 +28,23 @@ class SignView extends StatelessWidget { imgPath: "assets/image/icon_today_task.webp", moreText: S.of(context).renwuzhongxin, onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString('token') == null || - value.getString('token') == "") { - LoginTipsDialog().show(context); - } else { - Navigator.of(context).pushNamed('/router/integral_page'); - } - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + } else { + Navigator.of(context).pushNamed('/router/integral_page'); + } }, ), InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString('token') == null || - value.getString('token') == "") { - LoginTipsDialog().show(context); - } else { - Navigator.of(context).pushNamed('/router/integral_page') - .then((value) => { + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + } else { + Navigator.of(context).pushNamed('/router/integral_page') + .then((value) => { if (value != null) setSigned(value), - }); - } - }); + }); + } }, child: signIn(context), ), diff --git a/lib/home/home_view/top_selling_list.dart b/lib/home/home_view/top_selling_list.dart index 53ca1a2f..e07e96be 100644 --- a/lib/home/home_view/top_selling_list.dart +++ b/lib/home/home_view/top_selling_list.dart @@ -1,9 +1,11 @@ +import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:huixiang/data/good_list.dart'; import 'package:huixiang/data/home_rank.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/flutter_utils.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:huixiang/utils/font_weight.dart'; @@ -26,6 +28,7 @@ class _TopSellingList extends State { @override void initState() { + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); super.initState(); } diff --git a/lib/home/home_view/union_entry.dart b/lib/home/home_view/union_entry.dart index bde90cfb..75c7e40a 100644 --- a/lib/home/home_view/union_entry.dart +++ b/lib/home/home_view/union_entry.dart @@ -17,7 +17,6 @@ class UnionEntry extends StatefulWidget { } class _UnionEntry extends State { - ApiService? apiService; @override void initState() { diff --git a/lib/home/home_view/welfare_core.dart b/lib/home/home_view/welfare_core.dart index e0b2ff09..e35d8560 100644 --- a/lib/home/home_view/welfare_core.dart +++ b/lib/home/home_view/welfare_core.dart @@ -13,7 +13,6 @@ class WelfareCore extends StatefulWidget { } class _WelfareCore extends State { - ApiService? apiService; @override void initState() { diff --git a/lib/home/huixiang_brand_page.dart b/lib/home/huixiang_brand_page.dart index 2e5945ef..e43d3b6c 100644 --- a/lib/home/huixiang_brand_page.dart +++ b/lib/home/huixiang_brand_page.dart @@ -13,6 +13,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/main.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/store_title_tab.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -28,8 +29,7 @@ class BrandPage extends StatefulWidget { } } -class _BrandPage extends State - with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin { +class _BrandPage extends State with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin { final ScrollController scrollController = ScrollController(); final RefreshController refreshController = RefreshController(); @@ -45,17 +45,16 @@ class _BrandPage extends State msg: S.current.zhengzaijiazai, ); - final SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService( Dio(), context: context, - token: value.getString('token'), + token: SharedInstance.instance.token, ); BaseData? baseData = await apiService?.queryHome().catchError((error) { refreshController.refreshFailed(); - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { brandData = baseData!.data; @@ -67,22 +66,21 @@ class _BrandPage extends State "model": {"type": "BRAND_APP"}, }).catchError((error) { refreshController.refreshFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); bannerData.clear(); bannerData.addAll(banner?.data?.records ?? []); BaseData? brand = await apiService?.queryHomeBrand().catchError((error) { refreshController.refreshFailed(); - return Future.value(null); + return BaseData()..isSuccess = false; }); if (brand?.isSuccess ?? false) { brands.clear(); globaKeys.clear(); brands.addAll((brand!.data["brandList"] as List?) ?.map((e) => Brand.fromJson(e)) - .toList() ?? - []); + .toList() ?? []); founder = Founder.fromJson(brand.data["founder"]); brands.forEach((element) { globaKeys.add(GlobalKey()); diff --git a/lib/home/huixiang_view/huixiang_banner.dart b/lib/home/huixiang_view/huixiang_banner.dart index 71c9bef3..9f9aa910 100644 --- a/lib/home/huixiang_view/huixiang_banner.dart +++ b/lib/home/huixiang_view/huixiang_banner.dart @@ -69,20 +69,26 @@ class _HuiXiangBanner extends State { bannerClick(BannerData bannerData) async { switch (bannerData.contentType) { case 1: - Navigator.of(context).pushNamed('/router/integral_store_page', - arguments: {"goodsId": bannerData.content}); + Navigator.of(context).pushNamed( + '/router/integral_store_page', + arguments: {"goodsId": bannerData.content}, + ); break; case 2: - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "activityId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "activityId": bannerData.content, + }, + ); break; case 3: - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "articleId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', + arguments: { + "articleId": bannerData.content, + }, + ); break; case 4: String? router = bannerData.content; @@ -99,10 +105,12 @@ class _HuiXiangBanner extends State { } break; case 5: - Navigator.of(context) - .pushNamed('/router/class_details', arguments: { - "id": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/class_details', + arguments: { + "id": bannerData.content, + }, + ); break; case 7: String? router = bannerData.content; diff --git a/lib/home/huixiang_view/origin_info.dart b/lib/home/huixiang_view/origin_info.dart index cc09b260..6c402d5f 100644 --- a/lib/home/huixiang_view/origin_info.dart +++ b/lib/home/huixiang_view/origin_info.dart @@ -308,4 +308,5 @@ class _OriginInfo extends State { ), ); } + } diff --git a/lib/home/points_mall_page.dart b/lib/home/points_mall_page.dart index 6c3226c6..42ae9b03 100644 --- a/lib/home/points_mall_page.dart +++ b/lib/home/points_mall_page.dart @@ -18,6 +18,7 @@ import 'package:huixiang/home/points_mall_view/points_mall_banner.dart'; import 'package:huixiang/main.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -68,6 +69,8 @@ class _PointsMallPage extends State List bannerData = []; queryUser() async { + client ??= ApiService(Dio(), context: context, token: SharedInstance.instance.token, showLoading: false); + BaseData>? banner = await client?.queryBanner({ "model": {"type": "CREDIT_INDEX"}, }).catchError((onError) { @@ -82,11 +85,9 @@ class _PointsMallPage extends State BaseData? baseData = await client?.queryInfo().catchError((onError) { return BaseData()..isSuccess = false; }); - if (baseData?.isSuccess ?? false) { + if ((baseData?.isSuccess ?? false) && baseData?.data != null) { userInfo = baseData!.data; - SharedPreferences.getInstance().then((value) => { - value.setString('user', jsonEncode(baseData.data)), - }); + SharedInstance.instance.saveUser(baseData.data!); } } @@ -95,8 +96,7 @@ class _PointsMallPage extends State msg: S.current.zhengzaijiazai, ); - final SharedPreferences value = await SharedPreferences.getInstance(); - client = ApiService(Dio(), context: context, token: value.getString('token'), showLoading: false); + client = ApiService(Dio(), context: context, token: SharedInstance.instance.token, showLoading: false); await queryUser(); @@ -221,11 +221,12 @@ class _PointsMallPage extends State } _toDetails(index) async { - await Navigator.of(context).pushNamed('/router/integral_store_page', - arguments: {"goodsId": goods[index].id}); - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - String? token = sharedPreferences.getString("token"); - if (token?.isNotEmpty ?? false) queryUser(); + await Navigator.of(context).pushNamed( + '/router/integral_store_page', + arguments: {"goodsId": goods[index].id}, + ); + String token = SharedInstance.instance.token; + if (token.isNotEmpty) queryUser(); } @override diff --git a/lib/home/points_mall_view/point_mall_user.dart b/lib/home/points_mall_view/point_mall_user.dart index 77287a69..aa73d4a3 100644 --- a/lib/home/points_mall_view/point_mall_user.dart +++ b/lib/home/points_mall_view/point_mall_user.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -22,13 +23,12 @@ class _PointMallUser extends State { Widget build(BuildContext context) { return InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - Navigator.of(context).pushNamed('/router/new_login_page', - arguments: {"login": "login"}); - } - }); + if (SharedInstance.instance.token.isEmpty) { + Navigator.of(context).pushNamed( + '/router/new_login_page', + arguments: {"login": "login"}, + ); + } }, child: Container( margin: EdgeInsets.all(16), diff --git a/lib/home/points_mall_view/points_goods_title.dart b/lib/home/points_mall_view/points_goods_title.dart index 10edce32..010e2eb4 100644 --- a/lib/home/points_mall_view/points_goods_title.dart +++ b/lib/home/points_mall_view/points_goods_title.dart @@ -23,8 +23,8 @@ class PointsGoodsTitle extends StatefulWidget { } } -class _PointsGoodsTitle extends State - with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin{ +class _PointsGoodsTitle extends State with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin{ + var _itemText = S.current.morenpaixu; List sortString = [ S.current.morenpaixu, @@ -39,6 +39,7 @@ class _PointsGoodsTitle extends State @override Widget build(BuildContext context) { + super.build(context); return Container( margin: EdgeInsets.only(top:24.h), child: Column( diff --git a/lib/home/points_mall_view/points_goods_view.dart b/lib/home/points_mall_view/points_goods_view.dart index 7dd44c4e..d81c62cd 100644 --- a/lib/home/points_mall_view/points_goods_view.dart +++ b/lib/home/points_mall_view/points_goods_view.dart @@ -20,6 +20,7 @@ class PointGoods extends StatefulWidget { } class _PointGoods extends State { + String pointPrice(Goods goods) { if (goods.oneBean != "0") { return "${goods.oneBean}印章"; @@ -96,7 +97,7 @@ class _PointGoods extends State { offset: Offset(0, 3), blurRadius: 14, spreadRadius: 0, - ) + ), ], color: Colors.white, ), diff --git a/lib/home/points_mall_view/points_mall_banner.dart b/lib/home/points_mall_view/points_mall_banner.dart index 03337538..ed9a4609 100644 --- a/lib/home/points_mall_view/points_mall_banner.dart +++ b/lib/home/points_mall_view/points_mall_banner.dart @@ -73,20 +73,24 @@ class _PointMallBanner extends State { bannerClick(BannerData bannerData) async { switch (bannerData.contentType) { case 1: - Navigator.of(context).pushNamed('/router/integral_store_page', - arguments: {"goodsId": bannerData.content}); + Navigator.of(context).pushNamed( + '/router/integral_store_page', + arguments: {"goodsId": bannerData.content}, + ); break; case 2: - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "activityId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', arguments: { + "activityId": bannerData.content, + }, + ); break; case 3: - Navigator.of(context) - .pushNamed('/router/web_page', arguments: { - "articleId": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/web_page', arguments: { + "articleId": bannerData.content, + }, + ); break; case 4: String? router = bannerData.content; @@ -103,10 +107,11 @@ class _PointMallBanner extends State { } break; case 5: - Navigator.of(context) - .pushNamed('/router/class_details', arguments: { - "id": bannerData.content, - }); + Navigator.of(context).pushNamed( + '/router/class_details', arguments: { + "id": bannerData.content, + }, + ); break; case 7: String? router = bannerData.content; diff --git a/lib/home/trading_card_page.dart b/lib/home/trading_card_page.dart index c87a049a..995168d5 100644 --- a/lib/home/trading_card_page.dart +++ b/lib/home/trading_card_page.dart @@ -5,6 +5,7 @@ import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -29,11 +30,8 @@ class _TradingCardPage extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), context: context, token: value.getString("token")); - queryUserBalance(); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryUserBalance(); } @override diff --git a/lib/home/welfare_exchange.dart b/lib/home/welfare_exchange.dart index 0f1aee60..6ae90e9a 100644 --- a/lib/home/welfare_exchange.dart +++ b/lib/home/welfare_exchange.dart @@ -13,6 +13,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -54,25 +55,20 @@ class _WelfareExchange extends State @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, - token: value.getString("token"), - showLoading: false), - creditGoods(), - }); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); + creditGoods(); } queryUser() async { - BaseData? baseData = - await apiService?.queryInfo().catchError((onError) { + BaseData? baseData = await apiService?.queryInfo().catchError((onError) { return BaseData()..isSuccess = false; }); - if (baseData?.isSuccess ?? false) { - userInfo = baseData!.data; - SharedPreferences.getInstance().then((value) => { - value.setString('user', jsonEncode(baseData.data)), - }); + if ((baseData?.isSuccess ?? false) && baseData!.data != null) { + userInfo = baseData.data; + SharedInstance.instance.saveUser(baseData.data!); } } @@ -82,11 +78,9 @@ class _WelfareExchange extends State SmartDialog.showLoading( msg: S.current.zhengzaijiazai, ); - - final SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService(Dio(), context: context, - token: value.getString('token'), + token: SharedInstance.instance.token, showLoading: false); await queryUser(); @@ -106,8 +100,7 @@ class _WelfareExchange extends State gooods.addAll(goodsData?.data?.list ?? []); } - BaseData>? dataCategory = - await apiService?.goodsCategory({ + BaseData>? dataCategory = await apiService?.goodsCategory({ "current": 1, "map": {}, "model": {"pageNum": 1, "pageSize": 20, "searchKey": ""}, @@ -135,8 +128,7 @@ class _WelfareExchange extends State "pageSize": 100, "state": 1 }; - BaseData>? pageGoods = - await apiService?.creditGoods(param).catchError((onError) { + BaseData>? pageGoods = await apiService?.creditGoods(param).catchError((onError) { refreshController.loadFailed(); refreshController.refreshFailed(); return BaseData>()..isSuccess = false; @@ -465,7 +457,7 @@ class _WelfareExchange extends State Widget pointList() { return Container( - child: (goods?.isEmpty ?? true) + child: (goods.isEmpty) ? NoDataView( src: "assets/image/xiao_fei.webp", isShowBtn: false, diff --git a/lib/home/welfare_page.dart b/lib/home/welfare_page.dart index 2fcda1dd..22b31fc9 100644 --- a/lib/home/welfare_page.dart +++ b/lib/home/welfare_page.dart @@ -14,6 +14,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -51,16 +52,12 @@ class _WelfarePage extends State { @override void initState() { super.initState(); - if (apiService == null) { - SharedPreferences.getInstance().then((value) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - _onRefresh(); - }); - } + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + _onRefresh(); } queryGoods() async { @@ -73,11 +70,10 @@ class _WelfarePage extends State { "pageSize": 100, "state": 1 }; - BaseData>? pageGoods = - await apiService?.creditGoods(param).catchError((onError) { + BaseData>? pageGoods = await apiService?.creditGoods(param).catchError((onError) { refreshController.loadFailed(); refreshController.refreshFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); SmartDialog.dismiss(); if (pageGoods?.isSuccess ?? false) { @@ -98,9 +94,7 @@ class _WelfarePage extends State { "searchKey": "", "state": 0 }).catchError((onError) { - SmartDialog.showToast(AppUtils.dioErrorTypeToString(onError.type), - alignment: Alignment.center); - return Future.value(null); + return BaseData>()..isSuccess = false; }); coupons.clear(); coupon.clear(); @@ -158,9 +152,10 @@ class _WelfarePage extends State { height: 236.h, ), Expanded( - child: Container( - color: Colors.white, - )) + child: Container( + color: Colors.white, + ), + ) ], ), Scaffold( @@ -219,7 +214,7 @@ class _WelfarePage extends State { benefitExchange(), ], ), - ) + ), // activityTask(), ], ), @@ -445,8 +440,7 @@ class _WelfarePage extends State { style: TextStyle( fontSize: 16.sp, fontWeight: MyFontWeight.medium, - color: - cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), + color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), ), ), SizedBox( @@ -457,8 +451,7 @@ class _WelfarePage extends State { style: TextStyle( fontSize: 24.sp, fontWeight: MyFontWeight.semi_bold, - color: - cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), + color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), ), ), ], @@ -488,8 +481,7 @@ class _WelfarePage extends State { style: TextStyle( fontSize: 22.sp, fontWeight: MyFontWeight.semi_bold, - color: - cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), + color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), ), ), ], @@ -520,8 +512,7 @@ class _WelfarePage extends State { style: TextStyle( fontSize: 26.sp, fontWeight: MyFontWeight.semi_bold, - color: - cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), + color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), ), ), ], @@ -552,8 +543,7 @@ class _WelfarePage extends State { style: TextStyle( fontSize: 16.sp, fontWeight: MyFontWeight.medium, - color: - cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), + color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), ), ), SizedBox( @@ -566,8 +556,7 @@ class _WelfarePage extends State { style: TextStyle( fontSize: 24.sp, fontWeight: FontWeight.bold, - color: - cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), + color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), ), ), ], @@ -591,8 +580,7 @@ class _WelfarePage extends State { style: TextStyle( fontSize: 30.sp, fontWeight: MyFontWeight.semi_bold, - color: - cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), + color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), ), ), SizedBox( @@ -603,8 +591,7 @@ class _WelfarePage extends State { style: TextStyle( fontSize: 16.sp, fontWeight: MyFontWeight.semi_bold, - color: - cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), + color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060), ), ), ], @@ -693,7 +680,9 @@ class _WelfarePage extends State { ///领取优惠券 receiveCoupon(couponId) async { couponIndex = swiperIndex; - BaseData? baseData = await apiService?.receiveCoupon(couponId); + BaseData? baseData = await apiService?.receiveCoupon(couponId).catchError((error){ + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { queryCoupon(); showAlertDialog(); @@ -805,7 +794,7 @@ class _WelfarePage extends State { Icons.keyboard_arrow_right, color: Color(0xFF4D4D4D), size: 20, - ) + ), ], ), ), @@ -833,8 +822,7 @@ class _WelfarePage extends State { //垂直子Widget之间间距 mainAxisSpacing: 16.w, //子Widget宽高比例 0.59 - childAspectRatio: 200 / - (285 / 2 + (285 / 2) * AppUtils.textScale(context)), + childAspectRatio: 200 / (285 / 2 + (285 / 2) * AppUtils.textScale(context)), ), itemBuilder: (context, index) { return GestureDetector( @@ -847,7 +835,7 @@ class _WelfarePage extends State { child: exchangeItem(goods[index]), ); }, - ) + ), ], ), ); @@ -865,7 +853,7 @@ class _WelfarePage extends State { offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, - ) + ), ], ), child: Stack( diff --git a/lib/im/SocketClient.dart b/lib/im/SocketClient.dart index ff0b2fe3..11ad211f 100644 --- a/lib/im/SocketClient.dart +++ b/lib/im/SocketClient.dart @@ -12,18 +12,17 @@ import 'package:huixiang/im/database/message.dart'; import 'package:huixiang/im/out/auth.pb.dart'; import 'package:huixiang/im/out/message.pb.dart'; import 'package:huixiang/main.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:image_gallery_saver/image_gallery_saver.dart'; import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SocketClient { Socket? _socket; - SharedPreferences? _shared; Timer? timer; bool get heartbeatActive => timer != null && timer!.isActive; connect() async { - _shared = await SharedPreferences.getInstance(); if (_socket != null) { reconnect(); @@ -50,11 +49,9 @@ class SocketClient { Message message = Message.fromJson(messageMap); if (callbacks[dataResult.from] != null) { callbacks[dataResult.from]?.call(message); - /// user conversation callback } callbacks[userId]?.call(message); - /// user self conversation list callback }); }); @@ -66,7 +63,7 @@ class SocketClient { debugPrint("socket-listen-down: down"); }); - authRequest(_shared?.getString("token") ?? ""); + authRequest(SharedInstance.instance.token); heartbeat(); }).catchError((error) { @@ -257,5 +254,5 @@ class SocketClient { return true; } - String get userId => _shared?.getString("userId") ?? ""; + String get userId => SharedInstance.instance.userId; } diff --git a/lib/im/add_friend.dart b/lib/im/add_friend.dart index b61bca6e..5bbb882b 100644 --- a/lib/im/add_friend.dart +++ b/lib/im/add_friend.dart @@ -17,7 +17,6 @@ class AddFriend extends StatefulWidget { } class _AddFriend extends State { - ApiService? apiService; @override void initState() { diff --git a/lib/im/chat_details_page.dart b/lib/im/chat_details_page.dart index 18093ab5..a5cd9b7a 100644 --- a/lib/im/chat_details_page.dart +++ b/lib/im/chat_details_page.dart @@ -1,29 +1,30 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; -import 'dart:ui'; import 'package:dio/dio.dart'; import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; -import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:get/get.dart'; +import 'package:huixiang/constant.dart'; import 'package:huixiang/data/base_data.dart'; +import 'package:huixiang/data/im_user.dart'; import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/im/database/message.dart'; import 'package:huixiang/im/out/message.pb.dart'; import 'package:huixiang/main.dart'; -import 'package:huixiang/data/im_user.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; -import 'package:image_gallery_saver/image_gallery_saver.dart'; import 'package:image_pickers/image_pickers.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import '../../community/release_dynamic.dart'; import '../../generated/l10n.dart'; @@ -31,8 +32,7 @@ import '../../utils/font_weight.dart'; import '../utils/flutter_utils.dart'; import '../view_widget/custom_image.dart'; import '../view_widget/request_permission.dart'; -import 'im_view/on_chat_message.dart'; -import 'im_view/on_chat_msg_instance.dart'; + class ChatDetailsPage extends StatefulWidget { final Map? arguments; @@ -46,43 +46,39 @@ class ChatDetailsPage extends StatefulWidget { } class _ChatDetailsPage extends State - with WidgetsBindingObserver - implements OnChatMessage { + with WidgetsBindingObserver { ApiService? apiService; List mediaPaths = []; int selectCount = 9; int dynamicType = 0; final TextEditingController chatController = TextEditingController(); - bool emojiShowing = false; - double keyboard = -1; - bool needShowSmiley = false; - bool needHideSmiley = false; bool isKeyBoardShow = false; + bool emojiShowing = false; bool moreShow = false; - bool needShowMore = false; - bool needHideMore = false; + + double keyboard = -1; var commentFocus = FocusNode(); String hintText = "输入消息内容..."; UserInfo? userInfo; - final OnChatMessage? _tempOnChatMessage = OnChatMsgInstance.instance.onChatMessage; + // final OnChatMessage? _tempOnChatMessage = OnChatMsgInstance.instance.onChatMessage; final ScrollController scrollController = ScrollController(); + GlobalKey animatedListKey = GlobalKey(); String tex = ""; String selfUserId = ""; ImUser? _toUser; late String conversation; List imageUrl = []; - @override - void onMessage(txt) { - // SmartDialog.showToast("聊天 $txt", alignment: Alignment.center); - } + double inputWidgetHeight = 95; + double dynamicInputHeight = 0; RefreshController refreshController = RefreshController(); List messages = []; int page = 0; loadMessageList() async { - selfUserId = (await SharedPreferences.getInstance()).getString("userId") ?? ""; + selfUserId = SharedInstance.instance.userId; + debugPrint("selfUserId: $selfUserId _toUser?.mid: ${_toUser?.mid} "); conversation = conversationId(selfUserId, _toUser?.mid); ImUser? imUser = await hxDatabase.queryImUserById(conversation); @@ -95,9 +91,10 @@ class _ChatDetailsPage extends State await refresh(); socketClient.addCallback(_toUser?.mid ?? '', (Message message) { - messages.insert(0, message); - if (message.msgType == MsgType.VIDEO.value || message.msgType == MsgType.IMAGE.value) { - imageUrl.add(message.attach); + messages.add(message); + animatedListKey.currentState?.insertItem(messages.length - 1); + if ((message.msgType == MsgType.VIDEO.value || message.msgType == MsgType.IMAGE.value) && (message.attach?.isNotEmpty ?? false)) { + imageUrl.add(message.attach!); } messageShowTime().then((value) { refreshState(); @@ -107,66 +104,69 @@ class _ChatDetailsPage extends State messageImageUrl(); - refreshState(); - jumpToBottom(); + // refreshState(); + // jumpToBottom(); } - Future refresh() async { + Future refresh() async { List? messagePage = await hxDatabase.queryUList(conversation, page: page + 1, pageSize: 10); debugPrint("refresh-message-list: ${messagePage?.length ?? ''} page: $page"); if (messagePage?.isEmpty ?? true) { - refreshController.loadNoData(); - return; + refreshController.refreshCompleted(); + return 0; } else { - refreshController.loadComplete(); + refreshController.refreshCompleted(); page += 1; } + double height = 0; + await Future.forEach(messagePage!, (element) async { + height += await chatDetailsItemHeight(element); + }); + if (scrollController.hasClients) { + debugPrint("refresh-message-height: ${height} page: $page"); + scrollController.position.restoreOffset(height, initialRestore: true); + } if (page == 1) { - messages = messagePage!; + messages.addAll(messagePage.reversed.toList()); + animatedListKey.currentState?.insertAllItems(0, messagePage.length); } else { - messages.addAll(messagePage!); + messages.insertAll(0, messagePage.reversed.toList()); + animatedListKey.currentState?.insertAllItems(0, messagePage.length, duration: 300.milliseconds); } await messageShowTime(); - return Future.value(); + return height; } /// 消息中的图片 messageImageUrl() { - imageUrl = messages.where((e) => e.msgType == MsgType.VIDEO.value || e.msgType == MsgType.IMAGE.value).map((e) => e.attach).toList(); + imageUrl = messages.where((e) => (e.msgType == MsgType.VIDEO.value || e.msgType == MsgType.IMAGE.value) && (e.attach?.isNotEmpty ?? false)).map((e) => "${e.attach}").toList(); } Future messageShowTime() async { List? messagePages = await hxDatabase.queryTList(conversation); for (var value in messages) { - Message? message = messagePages?.firstWhere((element) => value.id == element.id); + Message? message = messagePages?.firstWhere((element) => value.id == element.id, orElse: () => messages.first); value.showTime = message != null; } } - SharedPreferences? sharedPre; - ///查询个人信息 queryUser() async { - sharedPre = await SharedPreferences.getInstance(); - if (apiService == null) - apiService = ApiService(Dio(), context: context, token: sharedPre?.getString("token")); - if ((sharedPre?.containsKey('user') ?? false) && - sharedPre?.getString('user') != null && - sharedPre?.getString('user') != "") { - userInfo = UserInfo.fromJson(jsonDecode(sharedPre!.getString('user')!)); - if (userInfo?.phone?.isNotEmpty ?? false) { - setState(() {}); - return; - } + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + + userInfo = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)); + if (userInfo?.phone?.isNotEmpty ?? false) { + setState(() {}); + return; } - BaseData? baseData = await apiService?.queryInfo().catchError((onError) {}); - if (baseData?.isSuccess ?? false) { + BaseData? baseData = await apiService?.queryInfo().catchError((onError) { + return BaseData()..isSuccess = false; + }); + if ((baseData?.isSuccess ?? false) && baseData?.data != null) { setState(() { userInfo = baseData!.data; }); - SharedPreferences.getInstance().then((value) => { - value.setString('user', jsonEncode(baseData!.data)), - }); + SharedInstance.instance.saveUser(baseData!.data!); } } @@ -174,75 +174,93 @@ class _ChatDetailsPage extends State if (mounted) setState(() {}); } + late StreamSubscription keyboardSubscription; + @override void initState() { super.initState(); _toUser = widget.arguments?["toUser"]; - OnChatMsgInstance.instance.onChatMessage = this; + // OnChatMsgInstance.instance.onChatMessage = this; WidgetsBinding.instance.addObserver(this); commentFocus.addListener(_focusNodeListener); queryUser(); loadMessageList(); - } - void jumpToBottom() { - Future.delayed(const Duration(milliseconds: 100), () { - scrollController.position.jumpTo(0); + scrollController.addListener(() { + debugPrint("scrollController-onChange: ${scrollController.position.pixels}"); + if (messages.length >= 10 && scrollController.position.pixels < -80) { + if (!loading) { + loading = true; + refresh().then((value) => loading = false); + } + } }); - } - void didChangeMetrics() { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) return; - isKeyBoardShow = MediaQuery.of(context).viewInsets.bottom > 0; - if (MediaQuery.of(context).viewInsets.bottom == 0) { - if (isKeyBoardShow) { - FocusScope.of(context).requestFocus(FocusNode()); - if (mounted) if (!emojiShowing) if (!moreShow) - setState(() { - hintText = "请输入消息内容..."; - isKeyBoardShow = false; - }); + var keyboardVisibilityController = KeyboardVisibilityController(); + keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) { + isKeyBoardShow = visible; + debugPrint("keyboardVisibility-onChange: ${isKeyBoardShow}"); + if (isKeyBoardShow) { + if (!emojiShowing && !moreShow) { + chatController.clear(); } } else { - if (mounted) - setState(() { - isKeyBoardShow = true; - }); + inputWidgetHeight = 95; } + jumpToBottom(); + // if (needShowSmiley && !visible) { + // needShowSmiley = false; + // setState(() { + // emojiShowing = true; + // }); + // } + // if (needHideSmiley && visible) { + // needHideSmiley = false; + // setState(() { + // emojiShowing = false; + // }); + // } + // if (needShowMore && !visible) { + // needShowMore = false; + // setState(() { + // moreShow = true; + // }); + // } + // if (needHideMore && visible) { + // needHideMore = false; + // setState(() { + // moreShow = false; + // }); + // } }); - if (needShowSmiley && window.viewInsets.bottom <= 0.1) { - needShowSmiley = false; - setState(() { - emojiShowing = true; - }); - } - if (needHideSmiley && window.viewInsets.bottom > 0.1) { - needHideSmiley = false; - setState(() { - emojiShowing = false; - }); - } - if (needShowMore && window.viewInsets.bottom <= 0.1) { - needShowMore = false; - setState(() { - moreShow = true; - }); - } - if (needHideMore && window.viewInsets.bottom > 0.1) { - needHideMore = false; - setState(() { - moreShow = false; - }); + } + + bool loading = false; + + void jumpToBottom() { + Future.delayed(const Duration(milliseconds: 400), () { + if (scrollController.hasClients && scrollController.position.pixels != scrollController.position.maxScrollExtent) { + scrollController.position.animateTo(scrollController.position.maxScrollExtent, duration: 250.milliseconds, curve: Curves.easeInOut); + } + }); + } + + @override + void didChangeMetrics() { + super.didChangeMetrics(); + dynamicInputHeight = MediaQuery.of(context).viewInsets.bottom; + if (dynamicInputHeight > 0 && dynamicInputHeight > keyboard) { + keyboard = dynamicInputHeight; } } @override void dispose() { super.dispose(); - OnChatMsgInstance.instance.onChatMessage = _tempOnChatMessage; + // OnChatMsgInstance.instance.onChatMessage = _tempOnChatMessage; + keyboardSubscription.cancel(); WidgetsBinding.instance.removeObserver(this); commentFocus.removeListener(_focusNodeListener); scrollController.dispose(); @@ -260,39 +278,51 @@ class _ChatDetailsPage extends State ///输入框点击事件 _onTextFieldTap() { if (emojiShowing) { - needHideSmiley = true; + emojiShowing = false; } if (moreShow) { - needHideMore = true; + moreShow = false; } } ///表情包点击事件 _onSmileyTap() { - if (!emojiShowing && commentFocus.hasFocus && isKeyBoardShow) { - needShowSmiley = true; + emojiShowing = !emojiShowing; + if (isKeyBoardShow && commentFocus.hasFocus) { commentFocus.unfocus(); + } + if (moreShow) { + moreShow = false; + } + if (emojiShowing) { + if (inputWidgetHeight == 95) { + inputWidgetHeight += (keyboard == -1 ? 270 : keyboard); + jumpToBottom(); + } } else { - setState(() { - emojiShowing = !emojiShowing; - isKeyBoardShow = emojiShowing; - moreShow = false; - }); + inputWidgetHeight = 95; } + setState(() {}); } ///更多点击事件 _onMoreTap() { - if (!moreShow && commentFocus.hasFocus && isKeyBoardShow) { - needShowMore = true; + moreShow = !moreShow; + if (isKeyBoardShow && commentFocus.hasFocus) { commentFocus.unfocus(); + } + if (emojiShowing) { + emojiShowing = false; + } + if (moreShow) { + if (inputWidgetHeight == 95) { + inputWidgetHeight += (keyboard == -1 ? 167 : keyboard); + jumpToBottom(); + } } else { - setState(() { - moreShow = !moreShow; - isKeyBoardShow = moreShow; - emojiShowing = false; - }); + inputWidgetHeight = 95; } + setState(() {}); } ///图片/视频选择 @@ -330,7 +360,8 @@ class _ChatDetailsPage extends State String fileUrl = await qiniu.uploadFile(apiService!, path); socketClient.sendMessage(_toUser?.mid ?? '', fileUrl, attach: path, msgType: galleryMode == GalleryMode.image ? 2 : 4).then((value) { Message message = value; - messages.insert(0, message); + messages.add(message); + animatedListKey.currentState?.insertItem(messages.length - 1); chatController.clear(); messageShowTime().then((value) { refreshState(); @@ -394,7 +425,8 @@ class _ChatDetailsPage extends State String fileUrl = await qiniu.uploadFile(apiService!, path); socketClient.sendMessage(_toUser?.mid ?? '', fileUrl, attach: path, msgType: 2).then((value) { Message message = value; - messages.insert(0, message); + messages.add(message); + animatedListKey.currentState?.insertItem(messages.length - 1); chatController.clear(); messageShowTime().then((value) { refreshState(); @@ -485,29 +517,21 @@ class _ChatDetailsPage extends State } @override - Widget build(BuildContext context) { - double h = MediaQuery.of(context).viewInsets.bottom; - if (h > 0) { - jumpToBottom(); - if (keyboard < h) { - keyboard = h; - // setState(() {}); - } - } + Widget build(BuildContext ctx) { return GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { - FocusScope.of(context).requestFocus(FocusNode()); setState(() { - needShowSmiley = false; emojiShowing = false; - isKeyBoardShow = emojiShowing; + isKeyBoardShow = false; moreShow = false; - isKeyBoardShow = moreShow; }); + inputWidgetHeight = 95; + FocusScope.of(context).requestFocus(FocusNode()); + // jumpToBottom(); }, child: Scaffold( - // resizeToAvoidBottomInset: false, + resizeToAvoidBottomInset: true, backgroundColor: Color(0xFFF6F6F6), appBar: MyAppBar( title: _toUser?.nickname, @@ -515,11 +539,16 @@ class _ChatDetailsPage extends State titleSize: 17.sp, leading: true, leadingColor: Colors.black, + toolbarHeight: kToolbarHeight, action: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () async { - await Navigator.of(context).pushNamed('/router/chat_setting', - arguments: {"userId": _toUser?.mid}); + await Navigator.of(context).pushNamed( + '/router/chat_setting', + arguments: { + "userId": _toUser?.mid, + }, + ); page = 0; refresh().then((value) { refreshState(); @@ -536,32 +565,11 @@ class _ChatDetailsPage extends State ), ), body: Container( + height: MediaQuery.of(context).size.height - kToolbarHeight - MediaQuery.of(context).padding.top - MediaQuery.of(context).viewInsets.bottom, child: Column( children: [ Expanded( - child: SmartRefresher( - enablePullDown: false, - enablePullUp: true, - header: MyHeader(), - footer: CustomFooter( - loadStyle: LoadStyle.ShowWhenLoading, - builder: (BuildContext context, LoadStatus? mode) { - return SizedBox(); - }, - ), - reverse: true, - scrollController: scrollController, - controller: refreshController, - onRefresh: () { - debugPrint(""); - }, - onLoading: () { - refresh().then((value) { - refreshState(); - }); - }, - child: chatDetailsList(), - ), + child: chatDetailsList(), flex: 1, ), input(), @@ -574,30 +582,68 @@ class _ChatDetailsPage extends State ///聊天列表 Widget chatDetailsList() { - return ListView.builder( - itemCount: messages.length, - reverse: true, - padding: EdgeInsets.zero, - itemBuilder: (context, position) { - return GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - setState(() { - if (emojiShowing) { - emojiShowing = !emojiShowing; - } - if (moreShow) { - moreShow = !moreShow; - } - }); - FocusScope.of(context).requestFocus(FocusNode()); - }, - child: chatDetailsItem(position), - ); + return AnimatedList( + key: animatedListKey, + initialItemCount: messages.length, + controller: scrollController, + physics: BouncingScrollPhysics()..frictionFactor(0.8), + itemBuilder: (context, position, animation) { + return chatDetailsItem(position); }, ); } + Future chatDetailsItemHeight(Message message) async { + bool isSelf = message.fromId == selfUserId; + bool isText = message.msgType == 1; + bool isImage = message.msgType == 2; + double itemHeight = 32.0; + if (message.showTime) { + itemHeight += 10.sp; + } + if (!isSelf && isText) { + itemHeight += 10.h; + double itemWidth = MediaQuery.of(context).size.width - 92.w - 44; + double textH = textHeight(message.content, 17.sp, 1.2, itemWidth) + 12; + itemHeight += textH > 44 ? textH : 44; + } + if (isSelf && isText) { + itemHeight += 10.h; + double itemWidth = MediaQuery.of(context).size.width - 88.w - 44; + if (message.state == 3) { + itemWidth -= 20; + itemWidth -= 12.w; + } + double textH = textHeight(message.content, 17.sp, 1.2, itemWidth) + 12; + itemHeight += textH > 44 ? textH : 44; + } + if (!isSelf && isImage) { + itemHeight += 10.h; + Size size = await fetchImageSize(message); + itemHeight += size.height; + } + if (isSelf && isImage) { + itemHeight += 10.h; + Size size = await fetchImageSize(message); + itemHeight += size.height; + } + return itemHeight; + } + + textHeight(text, fontSize, height, width) { + final TextPainter textPainter = TextPainter( + text: TextSpan( + text: text, + style: TextStyle( + fontSize: fontSize, + height: height, + ), + ), + textDirection: TextDirection.ltr, + )..layout(minWidth: 0, maxWidth: width); + return textPainter.height; + } + Widget chatDetailsItem(position) { bool isSelf = messages[position].fromId == selfUserId; bool isText = messages[position].msgType == 1; @@ -626,6 +672,7 @@ class _ChatDetailsPage extends State style: TextStyle( color: Color(0xFFA29E9E), fontSize: 10.sp, + height: 1.0, fontWeight: MyFontWeight.regular, ), ), @@ -662,6 +709,10 @@ class _ChatDetailsPage extends State GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { + if (_toUser?.mid?.isEmpty ?? true) { + "用户信息错误".toast; + return; + } Navigator.of(context).pushNamed( '/router/personal_page', arguments: { @@ -673,8 +724,8 @@ class _ChatDetailsPage extends State child: MImage( _toUser?.avatar ?? '', isCircle: true, - height: 44.h, - width: 44.h, + height: 44, + width: 44, fit: BoxFit.cover, errorSrc: "assets/image/default_1.webp", fadeSrc: "assets/image/default_1.webp", @@ -705,7 +756,7 @@ class _ChatDetailsPage extends State ), key: _buttonKey, padding: EdgeInsets.symmetric( - vertical: 8.h, + vertical: 6, horizontal: 12.w, ), child: Text( @@ -783,14 +834,14 @@ class _ChatDetailsPage extends State ), key: _buttonKey, padding: EdgeInsets.symmetric( - vertical: 8.h, + vertical: 6, horizontal: 12.w, ), child: Text( tex = messages[position].content, textAlign: TextAlign.left, style: TextStyle( - height: 1.2.h, + height: 1.2, color: Colors.white, fontSize: 17.sp, fontWeight: MyFontWeight.medium, @@ -809,7 +860,7 @@ class _ChatDetailsPage extends State Navigator.of(context).pushNamed( '/router/personal_page', arguments: { - "memberId": "0", + "memberId": selfUserId, "inletType": 1, }, ); @@ -817,8 +868,8 @@ class _ChatDetailsPage extends State child: MImage( userInfo?.headimg ?? "", isCircle: true, - height: 44.h, - width: 44.h, + height: 44, + width: 44, fit: BoxFit.cover, errorSrc: "assets/image/default_1.webp", fadeSrc: "assets/image/default_1.webp", @@ -831,7 +882,9 @@ class _ChatDetailsPage extends State /// not self image 图片 if (!isSelf && isImage) Padding( - padding: EdgeInsets.only(left: 17.w, right: 39.w, top: 20.h), + padding: EdgeInsets.only( + left: 17.w, right: 39.w, top: 10.h, + ), child: Row( children: [ MImage( @@ -851,19 +904,23 @@ class _ChatDetailsPage extends State showMessageMenu(context, _buttonKey, messages[position]); }, onTap: () { - if (imageUrl.contains(messages[position].attach)) { - ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach)); + if (imageUrl.contains(messages[position].attach) && (messages[position].attach?.isNotEmpty ?? false)) { + ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach!)); } }, child: FutureBuilder( future: fetchImageSize(messages[position]), key: _buttonKey, builder: (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.connectionState == - ConnectionState.waiting || - snapshot.hasError) { + if (messages[position].attach?.isEmpty ?? true) { + return SizedBox( + width: 180.w, + height: 200.h, + ); + } + if (snapshot.connectionState == ConnectionState.waiting || snapshot.hasError) { return Image.file( - File(messages[position].attach), + File(messages[position].attach!), width: 180.w, height: 200.h, alignment: Alignment.centerLeft, @@ -871,7 +928,7 @@ class _ChatDetailsPage extends State ); } else { return Image.file( - File(messages[position].attach), + File(messages[position].attach!), width: snapshot.data.width, height: snapshot.data.height, alignment: Alignment.centerLeft, @@ -892,7 +949,7 @@ class _ChatDetailsPage extends State padding: EdgeInsets.only( left: 39.w, right: 17.w, - top: 20.h, + top: 10.h, ), child: Row( children: [ @@ -902,17 +959,23 @@ class _ChatDetailsPage extends State showMessageMenu(context, _buttonKey, messages[position]); }, onTap: () { - if (imageUrl.contains(messages[position].attach)) { - ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach)); + if (imageUrl.contains(messages[position].attach) && (messages[position].attach?.isNotEmpty ?? false)) { + ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach!)); } }, child: FutureBuilder ( future: fetchImageSize(messages[position]), key: _buttonKey, builder: (BuildContext context, AsyncSnapshot snapshot) { + if (messages[position].attach?.isEmpty ?? true) { + return SizedBox( + width: 180.w, + height: 200.h, + ); + } if (snapshot.connectionState == ConnectionState.waiting || snapshot.hasError) { return Image.file( - File(messages[position].attach), + File(messages[position].attach!), width: 180.w, height: 200.h, alignment: Alignment.centerRight, @@ -920,7 +983,7 @@ class _ChatDetailsPage extends State ); } else { return Image.file( - File(messages[position].attach), + File(messages[position].attach!), width: snapshot.data.width, height: snapshot.data.height, alignment: Alignment.centerRight, @@ -1038,11 +1101,10 @@ class _ChatDetailsPage extends State GestureDetector( onTap: () async { await hxDatabase.deleteByMsgId("${message.id}"); + int index = messages.indexOf(message); messages.remove(message); + animatedListKey.currentState?.removeItem(index, (context, animation) {return Container();}); Navigator.pop(context); - if (mounted) { - setState(() {}); - } }, child: Column( children: [ @@ -1083,26 +1145,28 @@ class _ChatDetailsPage extends State } Future fetchImageSize(Message message) async { - String imageLocalPath = message.attach; + String? imageLocalPath = message.attach; String imageUrl = message.content; debugPrint("$imageLocalPath"); debugPrint("$imageUrl"); - File file = File(imageLocalPath); + if (imageLocalPath?.isEmpty ?? true) { + return Future.value(Size.zero); + } + + File file = File(imageLocalPath!); if (!(await file.exists())) { await qiniu.downloadFile(imageUrl, savePath: imageLocalPath); } Size size = Size.zero; - if (sharedPre != null) { - String? sizeStr = sharedPre!.getString(imageLocalPath); - if (sizeStr != null && sizeStr != "") { - Map sizeMap = jsonDecode(sizeStr); - size = Size(sizeMap["width"], sizeMap["height"]); - if (size != Size.zero) { - return size; - } + String? sizeStr = SharedInstance.instance.getSize(imageLocalPath); + if (sizeStr != null && sizeStr != "") { + Map sizeMap = jsonDecode(sizeStr); + size = Size(sizeMap["width"], sizeMap["height"]); + if (size != Size.zero) { + return size; } } @@ -1118,7 +1182,7 @@ class _ChatDetailsPage extends State "width": size.width, "height": size.height, }; - sharedPre?.setString(imageLocalPath, jsonEncode(sizeMap)); + SharedInstance.instance.setSize(imageLocalPath, jsonEncode(sizeMap)); completer.complete(size); })); return completer.future; @@ -1141,7 +1205,9 @@ class _ChatDetailsPage extends State Widget input() { return Container( color: Color(0xFFFDFCFC), - padding: EdgeInsets.only(top: 14.h, bottom: 15.h), + // duration: 400.milliseconds, + height: inputWidgetHeight, + padding: EdgeInsets.only(top: 14, bottom: 15), child: Column( children: [ ///输入框 @@ -1171,11 +1237,11 @@ class _ChatDetailsPage extends State if (commentText.trim() == "") { return; } - socketClient - .sendMessage(_toUser?.mid ?? '', commentText) + socketClient.sendMessage(_toUser?.mid ?? '', commentText) .then((value) { Message message = value; - messages.insert(0, message); + messages.add(message); + animatedListKey.currentState?.insertItem(messages.length - 1); chatController.clear(); messageShowTime().then((value) { refreshState(); @@ -1203,14 +1269,13 @@ class _ChatDetailsPage extends State behavior: HitTestBehavior.opaque, onTap: () { _onSmileyTap(); - jumpToBottom(); }, child: Container( padding: EdgeInsets.only(left: 15.w, right: 8.w), child: Image.asset( "assets/image/icon_chat_emo.webp", - height: 26.h, - width: 26.h, + height: 26, + width: 26, ), ), ), @@ -1218,27 +1283,25 @@ class _ChatDetailsPage extends State behavior: HitTestBehavior.opaque, onTap: () { _onMoreTap(); - jumpToBottom(); }, child: Container( padding: EdgeInsets.only(left: 8.w, right: 19.w), child: Image.asset( "assets/image/chat_more.webp", - height: 26.h, - width: 26.h, + height: 26, + width: 26, ), ), ), ], ), SizedBox( - height: 16.h, + height: 16, ), ///表情 - Offstage( - offstage: !emojiShowing, - child: SizedBox( + if (emojiShowing) + Container( height: keyboard == -1 ? 270 : keyboard, width: MediaQuery.of(context).size.width, child: EmojiPicker( @@ -1246,12 +1309,12 @@ class _ChatDetailsPage extends State config: Config( emojiViewConfig: EmojiViewConfig( columns: 7, - emojiSizeMax: 32 * (Platform.isIOS ? 1.10 : 1.0), + emojiSizeMax: 28 * (Platform.isIOS ? 1.10 : 1.0), verticalSpacing: 0, horizontalSpacing: 0, backgroundColor: const Color(0xFFF2F2F2), gridPadding: EdgeInsets.zero, - recentsLimit: 28, + recentsLimit: 35, replaceEmojiOnLimitExceed: false, noRecents: Text( "最近使用", @@ -1274,17 +1337,22 @@ class _ChatDetailsPage extends State categoryIcons: const CategoryIcons(), tabIndicatorAnimDuration: Duration(milliseconds: 0), ), + bottomActionBarConfig: const BottomActionBarConfig( + backgroundColor: Colors.transparent, + buttonIconColor: Colors.blue, + showBackspaceButton: true, + showSearchViewButton: false, + ), + swapCategoryAndBottomBar: false, checkPlatformCompatibility: true, ), ), ), - ), ///更多 - Offstage( - offstage: !moreShow, - child: Container( - height: keyboard == -1 ? 167.h : keyboard, + if (moreShow) + Container( + height: keyboard == -1 ? 167 : keyboard, child: Column( children: [ Container( @@ -1383,7 +1451,6 @@ class _ChatDetailsPage extends State ], ), ), - ), ], ), ); @@ -1394,4 +1461,5 @@ class _ChatDetailsPage extends State debugPrint(tex); Clipboard.setData(ClipboardData(text: tex)); } + } diff --git a/lib/im/chat_friend_group.dart b/lib/im/chat_friend_group.dart index ae86eb1b..c07138d2 100644 --- a/lib/im/chat_friend_group.dart +++ b/lib/im/chat_friend_group.dart @@ -1,19 +1,15 @@ -import 'dart:ui'; import 'package:dio/dio.dart'; -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/social_info.dart'; +import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; -import 'package:shared_preferences/shared_preferences.dart'; +import 'package:huixiang/view_widget/my_tab.dart'; -import '../../generated/l10n.dart'; -import '../view_widget/my_tab.dart'; import 'im_view/custom_underline_tabIndicator.dart'; import 'im_view/friend_groip_list.dart'; @@ -56,11 +52,13 @@ class _ChatFriendGroup extends State ///个人社交信息(粉丝/关注数量/成就数量/好友数量) querySocialInfo() async { - SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService(Dio(), - context: context, token: value.getString("token"), showLoading: false); + context: context, token: SharedInstance.instance.token, showLoading: false, + ); - BaseData? baseData = await apiService?.socialInfo().catchError((onError) {}); + BaseData? baseData = await apiService?.socialInfo().catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { infoNumber = baseData!.data; diff --git a/lib/im/chat_setting.dart b/lib/im/chat_setting.dart index c5fe2338..548420fa 100644 --- a/lib/im/chat_setting.dart +++ b/lib/im/chat_setting.dart @@ -1,13 +1,11 @@ -import 'dart:ui'; import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/im/database/message.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:flutter/cupertino.dart'; -import 'package:shared_preferences/shared_preferences.dart'; + import '../../utils/font_weight.dart'; import '../main.dart'; import '../data/im_user.dart'; @@ -34,11 +32,9 @@ class _ChatSetting extends State { } void initData() async { - selfUserId = (await SharedPreferences.getInstance()).getString("userId") ?? ""; + selfUserId = SharedInstance.instance.userId; imUser = await hxDatabase.queryImUserById(widget.arguments?["userId"]); - setState(() { - - }); + setState(() {}); } @override diff --git a/lib/im/contact_share.dart b/lib/im/contact_share.dart index 576b6f98..822982d8 100644 --- a/lib/im/contact_share.dart +++ b/lib/im/contact_share.dart @@ -1,14 +1,7 @@ -import 'dart:ui'; - import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; -import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; -import 'package:flutter/cupertino.dart'; - -import '../../utils/font_weight.dart'; class ContactsShare extends StatefulWidget { final Map? arguments; @@ -22,7 +15,6 @@ class ContactsShare extends StatefulWidget { } class _ContactsShare extends State { - ApiService? apiService; final TextEditingController searchController = TextEditingController(); int searchIndex = 0; @@ -43,92 +35,105 @@ class _ContactsShare extends State { titleColor: Colors.black, ), body: Container( - margin: EdgeInsets.only(top:14.h), + margin: EdgeInsets.only(top: 14.h), color: Colors.white, - child:SingleChildScrollView( - physics: BouncingScrollPhysics(), - child: GestureDetector( + child: SingleChildScrollView( + physics: BouncingScrollPhysics(), + child: GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { FocusScope.of(context).requestFocus(FocusNode()); }, - child:Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - contactSearch(), - Padding( - padding: EdgeInsets.only(left: 17.w,bottom:24.h), - child: Text("最近联系(0)", - style: TextStyle( - fontSize: 17.sp, - color: Color(0xFF0D0D0D), - fontWeight: MyFontWeight.regular, - )), - ), - recentList(), - Padding( - padding: EdgeInsets.only(left: 17.w,bottom:24.h), - child: Text("我的关注(0)", - style: TextStyle( - fontSize: 17.sp, - color: Color(0xFF0D0D0D), - fontWeight: MyFontWeight.regular, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + contactSearch(), + Padding( + padding: EdgeInsets.only( + left: 17.w, bottom: 24.h, ), - ), + child: Text( + "最近联系(0)", + style: TextStyle( + fontSize: 17.sp, + color: Color(0xFF0D0D0D), + fontWeight: MyFontWeight.regular, + ), + ), + ), + recentList(), + Padding( + padding: EdgeInsets.only( + left: 17.w, + bottom: 24.h, + ), + child: Text( + "我的关注(0)", + style: TextStyle( + fontSize: 17.sp, + color: Color(0xFF0D0D0D), + fontWeight: MyFontWeight.regular, + ), + ), + ), + mineFollowList(), + ], ), - mineFollowList(), - ], - )),) + ), + ), ), ); } Widget contactSearch() { return Container( - width: double.infinity, - margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 16.h), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(6.w), - color: Color(0xFFF9FAF7), - ), - child: Stack( - alignment: Alignment.center, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Image.asset( - "assets/image/icon_search.webp", - fit: BoxFit.fill, - ), - SizedBox( - width: 4.w, - ), - Text("搜索", - style: TextStyle( - fontSize: 12.sp, - color: Color(0xFFB3B3B3), - fontWeight: MyFontWeight.regular, - )), - ], - ), - TextField( - textInputAction: TextInputAction.search, - enableInteractiveSelection: true, - onEditingComplete: () { - - }, - controller: searchController, - cursorHeight: 25.h, - decoration: InputDecoration( - contentPadding: EdgeInsets.only(top: 7.h, bottom: 9.h,left:5.w), - border: InputBorder.none, + width: double.infinity, + margin: EdgeInsets.only( + left: 16.w, right: 16.w, top: 4.h, bottom: 16.h, + ), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(6.w), + color: Color(0xFFF9FAF7), + ), + child: Stack( + alignment: Alignment.center, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Image.asset( + "assets/image/icon_search.webp", + fit: BoxFit.fill, + ), + SizedBox( + width: 4.w, + ), + Text("搜索", + style: TextStyle( + fontSize: 12.sp, + color: Color(0xFFB3B3B3), + fontWeight: MyFontWeight.regular, + ), + ), + ], ), - ) - ], - ) + TextField( + textInputAction: TextInputAction.search, + enableInteractiveSelection: true, + onEditingComplete: () {}, + controller: searchController, + cursorHeight: 25.h, + decoration: InputDecoration( + contentPadding: EdgeInsets.only( + top: 7.h, bottom: 9.h, left: 5.w, + ), + border: InputBorder.none, + ), + ) + ], + ), ); } @@ -142,48 +147,47 @@ class _ContactsShare extends State { onTap: () {}, child: recentItem(), ); - }); + }, + ); } Widget recentItem() { return Container( - margin: EdgeInsets.only(bottom: 14.h), - padding: EdgeInsets.only(left: 16.w,right: 14.w), - child:Column( - children: [ - Row( - children: [ - // MImage( - // "", - // isCircle: true, - // width: 44, - // height: 44, - // fit: BoxFit.cover, - // errorSrc: "assets/image/default_1.webp", - // fadeSrc: "assets/image/default_1.webp", - // ), - Image.asset( - "assets/image/fuka_zj.webp", - height:44, - width:44, + margin: EdgeInsets.only(bottom: 14.h), + padding: EdgeInsets.only( + left: 16.w, right: 14.w, + ), + child: Column( + children: [ + Row( + children: [ + Image.asset( + "assets/image/fuka_zj.webp", + height: 44, + width: 44, + ), + SizedBox( + width: 10.w, + ), + Text("张五", + style: TextStyle( + fontSize: 14.sp, + color: Color(0xFF1A1A1A), + fontWeight: MyFontWeight.bold, + ), + ), + ], + ), + Container( + height: 1.h, + width: double.infinity, + color: Color(0xFFF7F7F7), + margin: EdgeInsets.only( + left: 54.w, top: 10.h, ), - SizedBox(width: 10.w,), - Text("张五", - style: TextStyle( - fontSize: 14.sp, - color: Color(0xFF1A1A1A), - fontWeight: MyFontWeight.bold, - )), - ], - ), - Container( - height: 1.h, - width: double.infinity, - color: Color(0xFFF7F7F7), - margin: EdgeInsets.only(left:54.w,top: 10.h), - ) - ], - ) + ) + ], + ), ); } @@ -197,48 +201,47 @@ class _ContactsShare extends State { onTap: () {}, child: recentItem(), ); - }); + }, + ); } Widget mineFollowItem() { return Container( margin: EdgeInsets.only(bottom: 14.h), - padding: EdgeInsets.only(left: 16.w,right: 14.w), - child:Column( + padding: EdgeInsets.only( + left: 16.w, right: 14.w, + ), + child: Column( children: [ Row( children: [ - // MImage( - // "", - // isCircle: true, - // width: 44, - // height: 44, - // fit: BoxFit.cover, - // errorSrc: "assets/image/default_1.webp", - // fadeSrc: "assets/image/default_1.webp", - // ), Image.asset( "assets/image/fuka_zj.webp", - height:44, - width:44, + height: 44, + width: 44, + ), + SizedBox( + width: 10.w, ), - SizedBox(width: 10.w,), Text("小王", style: TextStyle( fontSize: 14.sp, color: Color(0xFF1A1A1A), fontWeight: MyFontWeight.bold, - )), + ), + ), ], ), Container( height: 1.h, width: double.infinity, color: Color(0xFFF7F7F7), - margin: EdgeInsets.only(left:54.w,top: 10.h), - ) + margin: EdgeInsets.only( + left: 54.w, top: 10.h, + ), + ), ], - ) + ), ); } } diff --git a/lib/im/database/hx_database.dart b/lib/im/database/hx_database.dart index 96857ce1..7613278e 100644 --- a/lib/im/database/hx_database.dart +++ b/lib/im/database/hx_database.dart @@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart'; import 'package:huixiang/constant.dart'; import 'package:huixiang/im/database/message.dart'; import 'package:huixiang/im/database/migration.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sqflite/sqflite.dart'; @@ -38,8 +39,7 @@ class HxDatabase { _dbIsOpen() async { if (db == null || !db!.isOpen) { - var sp = await SharedPreferences.getInstance(); - open(key: sp.getString("userId")); + open(key: SharedInstance.instance.userId); } } diff --git a/lib/im/database/message.dart b/lib/im/database/message.dart index 059fe096..15c99a49 100644 --- a/lib/im/database/message.dart +++ b/lib/im/database/message.dart @@ -19,11 +19,11 @@ class Message { String toId; - String replyId; + String? replyId; String content; - String attach; + String? attach; int msgType; diff --git a/lib/im/im_search.dart b/lib/im/im_search.dart index 92831e8f..3b56c281 100644 --- a/lib/im/im_search.dart +++ b/lib/im/im_search.dart @@ -2,7 +2,9 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:huixiang/constant.dart'; import 'package:huixiang/data/base_list_data.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../data/im_user.dart'; @@ -33,9 +35,7 @@ class _ImSearch extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - selfUserId = value.getString("userId") ?? ""; - }); + selfUserId = SharedInstance.instance.userId; } ///离开页面记着销毁和清除 @@ -47,13 +47,10 @@ class _ImSearch extends State { ///搜索列表 queryImSearch(keyword) async { - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService(Dio(), - context: context, - token: value.getString("token"), - showLoading: false); - } + apiService ??= ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); BaseListData? baseData = await apiService?.memberSearch(keyword).catchError((onError) { return BaseListData()..isSuccess = false; @@ -129,72 +126,78 @@ class _ImSearch extends State { ) : Expanded( child: Column( - children: [ - Padding( - padding: EdgeInsets.only(bottom: 19.h), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (editingController.text != "" && - searchState == 1) - Padding( - padding: EdgeInsets.only(left: 16.w), - child: Text( - "搜索用户:", - textAlign: TextAlign.center, - style: TextStyle( - color: Color(0xFF060606), - fontSize: 16.sp, - fontWeight: MyFontWeight.medium, + children: [ + Padding( + padding: EdgeInsets.only(bottom: 19.h), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (editingController.text != "" && + searchState == 1) + Padding( + padding: EdgeInsets.only(left: 16.w), + child: Text( + "搜索用户:", + textAlign: TextAlign.center, + style: TextStyle( + color: Color(0xFF060606), + fontSize: 16.sp, + fontWeight: MyFontWeight.medium, + ), ), ), - ), - if (editingController.text != "" && - searchState == 1) - Expanded( - child: Text( - editingController?.text ?? "", - style: TextStyle( - fontSize: 16.sp, - color: Color(0xFF32A060), - fontWeight: MyFontWeight.regular), - )) - ], + if (editingController.text != "" && + searchState == 1) + Expanded( + child: Text( + editingController?.text ?? "", + style: TextStyle( + fontSize: 16.sp, + color: Color(0xFF32A060), + fontWeight: MyFontWeight.regular), + )) + ], + ), ), - ), - if (editingController.text != "" && searchState == 1) - Expanded( + if (editingController.text != "" && searchState == 1) + Expanded( child: ListView.builder( - itemCount: searchUser?.length ?? 0, - physics: BouncingScrollPhysics(), - shrinkWrap: true, - itemBuilder: (context, position) { - return GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - setState(() { - searchUserIndex = position; - }); - Navigator.of(context).pushNamed( - '/router/personal_page', - arguments: { - "memberId": (searchUser[searchUserIndex] - .mid ?? - "") == - selfUserId - ? "0" - : searchUser[searchUserIndex].mid, - "inletType": 0 + itemCount: searchUser?.length ?? 0, + physics: BouncingScrollPhysics(), + shrinkWrap: true, + itemBuilder: (context, position) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + setState(() { + searchUserIndex = position; }); - FocusScope.of(context) - .requestFocus(FocusNode()); + String memberId = searchUser[searchUserIndex].mid ?? ""; + if (memberId.isEmpty) { + "用户信息错误".toast; + return; + } + if (memberId == selfUserId) { + return; + } + Navigator.of(context).pushNamed( + '/router/personal_page', + arguments: { + "memberId": memberId, + "inletType": 0 + }, + ); + FocusScope.of(context) + .requestFocus(FocusNode()); + }, + child: imSearchItem(searchUser[position]), + ); }, - child: imSearchItem(searchUser[position]), - ); - }, - )) - ], - )), + ), + ) + ], + ), + ), ], ), ), diff --git a/lib/im/im_view/friend_groip_list.dart b/lib/im/im_view/friend_groip_list.dart index 89960dc8..49dd823f 100644 --- a/lib/im/im_view/friend_groip_list.dart +++ b/lib/im/im_view/friend_groip_list.dart @@ -1,15 +1,13 @@ import 'package:dio/dio.dart'; -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/follow.dart'; import 'package:huixiang/data/page.dart'; -import 'package:huixiang/main.dart'; import 'package:huixiang/data/im_user.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import '../../retrofit/retrofit_api.dart'; import 'package:huixiang/im/database/message.dart'; @@ -54,30 +52,12 @@ class _FriendGroupList extends State { super.dispose(); } - // loadMessageList() async { - // SharedPreferences shared = await SharedPreferences.getInstance(); - // String userId = shared.getString("userId"); - // messages = await hxDatabase.queryList(userId); - // messages.forEach((element) { - // debugPrint("messages: ${element.toJson()}"); - // }); - // userIds = messages - // .map((e) => e.toId != userId ? e.toId : e.fromId) - // .toSet().where((element) => element != userId) - // .toList(); - // if (mounted) { - // setState(() {}); - // } - // - // } - ///关注、粉丝列表 queryFollowList() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); apiService ??= ApiService( Dio(), context: context, - token: sharedPreferences.getString("token"), + token: SharedInstance.instance.token, showLoading: false, ); @@ -104,11 +84,10 @@ class _FriendGroupList extends State { ///好友列表 queryMutualFollowList() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); apiService ??= ApiService( Dio(), context: context, - token: sharedPreferences.getString("token"), + token: SharedInstance.instance.token, showLoading: false, ); @@ -163,7 +142,7 @@ class _FriendGroupList extends State { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - if (list![position].mid == sharedPreferences.getString("userId")) { + if (list![position].mid == SharedInstance.instance.userId) { SmartDialog.showToast("不能跟自己聊天", alignment: Alignment.center); return; } @@ -171,9 +150,9 @@ class _FriendGroupList extends State { '/router/chat_details_page', arguments: { "toUser": ImUser( - avatar: list![position].avatar, - mid: list![position].mid, - nickname: list![position].nickname, + avatar: list![position].avatar, + mid: list![position].mid, + nickname: list![position].nickname, ), }, ); diff --git a/lib/im/im_view/im_page.dart b/lib/im/im_view/im_page.dart index 5f9a14f9..23322981 100644 --- a/lib/im/im_view/im_page.dart +++ b/lib/im/im_view/im_page.dart @@ -1,6 +1,7 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; +import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:huixiang/constant.dart'; import 'package:huixiang/data/base_list_data.dart'; @@ -10,6 +11,7 @@ import 'package:huixiang/im/database/message.dart'; import 'package:huixiang/main.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/round_button.dart'; @@ -60,38 +62,31 @@ class _IMPage extends State implements OnChatMessage { @override void dispose() { super.dispose(); - OnChatMsgInstance.instance.onChatMessage = null; + // OnChatMsgInstance.instance.onChatMessage = null; socketClient.removeCallback(socketClient.userId); } @override void initState() { super.initState(); - OnChatMsgInstance.instance.onChatMessage = this; + // OnChatMsgInstance.instance.onChatMessage = this; initSocketClient(); - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), token: value.getString("token"), context: context); - queryMsgStats(); - }); + apiService = ApiService(Dio(), token: SharedInstance.instance.token, context: context); + queryMsgStats(); } initSocketClient() async { - SharedPreferences shared = await SharedPreferences.getInstance(); - selfUserId = shared.getString("userId") ?? ''; + selfUserId = SharedInstance.instance.userId; socketClient.addCallback(selfUserId, (Message message) { if (conversationIds.contains(message.conversationId)) { conversationIds.remove(message.conversationId); } conversationIds.insert(insertIndex, message.conversationId); - lastMessageMap[message.conversationId] = message; - listenerRefresh(message); }); - loadMessageList(); } @@ -149,7 +144,7 @@ class _IMPage extends State implements OnChatMessage { /// update imuser info by mids queryImUserInfo(userIds) async { List contacts = (await hxDatabase.queryImUser(userIds)) ?? []; - if (contacts?.isEmpty ?? true) { + if (contacts.isEmpty) { await queryMemberInfo(userIds); return; } else { @@ -166,10 +161,11 @@ class _IMPage extends State implements OnChatMessage { .mGroupItem(); List topConversationIds = [], notTopUserIds = []; contactMap.forEach((key, value) { - if (value.isTop == 1) + if (value.isTop == 1) { topConversationIds.add(key); - else + } else { notTopUserIds.add(key); + } }); insertIndex = topConversationIds.length; this.conversationIds = topConversationIds..addAll(notTopUserIds); @@ -178,8 +174,6 @@ class _IMPage extends State implements OnChatMessage { /// update one conversation last message ,and update conversation sort void updateLastMessage(String conversationId) async { Message? message = await hxDatabase.lastMessage(conversationId); - debugPrint( - "lastmessage: $conversationId ${message?.content} ${message?.toJson()}"); if (message != null) { lastMessageMap[conversationId] = message; await sortConversation(lastMessageMap); @@ -205,10 +199,7 @@ class _IMPage extends State implements OnChatMessage { BaseListData? baseData = await apiService?.memberInfoByIds({ "mids": mids, }).catchError((error) { - SmartDialog.showToast( - AppUtils.dioErrorTypeToString(error.type), - alignment: Alignment.center, - ); + return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (baseData!.data?.isNotEmpty ?? false) { @@ -222,25 +213,17 @@ class _IMPage extends State implements OnChatMessage { }); refreshState(); } - } else { - if (baseData?.msg?.isNotEmpty ?? false) { - SmartDialog.showToast(baseData?.msg ?? '', alignment: Alignment.center); - } } } ///App消息 统计各类消息数量 queryMsgStats() async { - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } - BaseListData? baseData = - await apiService?.stats().catchError((error) { + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + BaseListData? baseData = await apiService?.stats().catchError((error) { return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -304,9 +287,7 @@ class _IMPage extends State implements OnChatMessage { GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - Navigator.of(context) - .pushNamed('/router/chat_friend_group') - .then((value) { + Navigator.of(context).pushNamed('/router/chat_friend_group').then((value) { _refresh(); }); }, @@ -337,9 +318,7 @@ class _IMPage extends State implements OnChatMessage { footer: CustomFooter( loadStyle: LoadStyle.ShowWhenLoading, builder: (BuildContext context, LoadStatus? mode) { - return (messages.length == 0) - ? Container() - : MyFooter(mode); + return (messages.length == 0) ? Container() : MyFooter(mode); }, ), controller: _refreshController, @@ -367,7 +346,8 @@ class _IMPage extends State implements OnChatMessage { "assets/image/icon_system_message_new.webp", S.of(context).xitongxiaoxi, ((msgNumber["2"] ?? 0) + (msgNumber["3"] ?? 0)) - .toString()), + .toString(), + ), ), GestureDetector( behavior: HitTestBehavior.opaque, @@ -434,7 +414,7 @@ class _IMPage extends State implements OnChatMessage { }); }, child: Container( - margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 16.h), + margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 8.h), padding: EdgeInsets.symmetric(vertical: 10.h), decoration: BoxDecoration( color: Color(0xFFFDFCFC), @@ -465,220 +445,153 @@ class _IMPage extends State implements OnChatMessage { ); } - bool _isDelEnter = false; - Map idsController = {}; - String? lastScrollId; - double lastScrollOffset = 0; - bool _isScrollOpen = false; - ///聊天列表 Widget chatList() { return ListView( - padding: EdgeInsets.only(top: 8.h), + padding: EdgeInsets.zero, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), children: conversationIds.map((e) { - ScrollController scrollController; - if (idsController.containsKey(e)) - scrollController = idsController[e] ?? ScrollController(); - else { - scrollController = ScrollController(); - idsController[e] = scrollController; - } - scrollController.addListener(() { - if (scrollController.offset > 0) { - if (lastScrollId != null && lastScrollId != e) - idsController[lastScrollId]?.jumpTo(0); - if (lastScrollOffset < scrollController.offset) { - scrollController - .jumpTo(scrollController.position.maxScrollExtent); - _isScrollOpen = true; - } else if (lastScrollOffset > scrollController.offset && - _isScrollOpen) { - scrollController.jumpTo(0); - } - lastScrollId = e; - // scrollController.animateTo( - // lastScrollOffset == scrollController.position.maxScrollExtent - // ? 0 - // : scrollController.position.maxScrollExtent, - // duration: Duration(milliseconds: 100), - // curve: Curves.ease); - lastScrollOffset = scrollController.offset; - } else { - if (lastScrollId == e) { - setState(() { - _isDelEnter = false; - _isScrollOpen = false; - }); - } - } - }); int position = conversationIds.indexOf(e); - return SingleChildScrollView( - physics: BouncingScrollPhysics(), - controller: scrollController, - scrollDirection: Axis.horizontal, - child: Row( - children: [ - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - Navigator.of(context).pushNamed( - '/router/chat_details_page', - arguments: { - "toUser": contactMap[conversationIds[position]], - }, - ).then((value) { - unreadCountMap[conversationIds[position]] = 0; - updateLastMessage(conversationIds[position]); - _refresh(); - }); - }, - child: chatItem(conversationIds[position]), - ), - GestureDetector( - child: Container( - color: Colors.red, - alignment: Alignment.center, - padding: - EdgeInsets.symmetric(vertical: 25.h, horizontal: 14.w), - child: Text( - _isDelEnter && lastScrollId == e - ? "删除并清空" - : S.of(context).shanchu, - style: TextStyle( - color: Colors.white, - fontSize: 14.sp, - fontWeight: MyFontWeight.regular, - ), - ), - ), - onTap: () async { - // showDelDialog(conversationIds[position]); - if (_isDelEnter) { - await hxDatabase.deleteByUser(conversationIds[position]); - lastScrollId = null; - _refresh(); - } else { - Future.delayed(Duration(milliseconds: 100), () { - idsController[lastScrollId]?.animateTo( - idsController[lastScrollId]!.position.maxScrollExtent, - duration: Duration(milliseconds: 100), - curve: Curves.ease); - }); - } - setState(() { - _isDelEnter = !_isDelEnter; - }); - }, - ), - ], - ), + return InkWell( + onTap: () { + Navigator.of(context).pushNamed( + '/router/chat_details_page', + arguments: { + "toUser": contactMap[conversationIds[position]], + }, + ).then((value) { + unreadCountMap[conversationIds[position]] = 0; + updateLastMessage(conversationIds[position]); + _refresh(); + }); + }, + child: chatItem(e), ); }).toList(), ); } Widget chatItem(conversationId) { - return Container( - padding: EdgeInsets.only( - left: 16.w, - right: 17.w, - bottom: 18.h, - ), - width: MediaQuery.of(context).size.width, - child: Row( + return Slidable( + key: ValueKey(conversationId), + direction: Axis.horizontal, + closeOnScroll: true, + endActionPane: ActionPane( + dragDismissible: true, + extentRatio: 0.25, + motion: const ScrollMotion(), children: [ - MImage( - !contactMap.containsKey(conversationId) - ? "" - : contactMap[conversationId]?.avatar ?? "", - isCircle: true, - height: 54.h, - width: 54.h, - fit: BoxFit.cover, - errorSrc: "assets/image/default_1.webp", - fadeSrc: "assets/image/default_1.webp", - ), - SizedBox( - width: 12.w, + SlidableAction( + onPressed: (BuildContext context) async { + await hxDatabase.deleteByUser(conversationId); + _refresh(); + }, + backgroundColor: Color(0xFFFE4A49), + foregroundColor: Colors.white, + autoClose: true, + label: S.of(context).shanchu, ), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Expanded( - child: Text( - !contactMap.containsKey(conversationId) - ? "" - : contactMap[conversationId]?.nickname ?? "", - // overflow: TextOverflow.fade, - maxLines: 1, - style: TextStyle( - fontSize: 16.sp, - color: Color(0xFF060606), - fontWeight: MyFontWeight.semi_bold, + ], + ), + child: Container( + padding: EdgeInsets.only( + left: 16.w, + right: 17.w, + top: 8.h, + bottom: 8.h, + ), + width: MediaQuery.of(context).size.width, + child: Row( + children: [ + MImage( + !contactMap.containsKey(conversationId) ? "" : contactMap[conversationId]?.avatar ?? "", + isCircle: true, + height: 54, + width: 54, + fit: BoxFit.cover, + errorSrc: "assets/image/default_1.webp", + fadeSrc: "assets/image/default_1.webp", + ), + SizedBox( + width: 12.w, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + !contactMap.containsKey(conversationId) + ? "" + : contactMap[conversationId]?.nickname ?? "", + // overflow: TextOverflow.fade, + maxLines: 1, + style: TextStyle( + fontSize: 16.sp, + color: Color(0xFF060606), + fontWeight: MyFontWeight.semi_bold, + ), ), ), - ), - Text( - lastMessageMap[conversationId]?.time != null - ? AppUtils.timeFormatter( - DateTime.fromMillisecondsSinceEpoch(int.parse( - lastMessageMap[conversationId]?.time ?? ""))) - : "", - style: TextStyle( - fontSize: 12.sp, - color: Color(0xFFA29E9E), - fontWeight: MyFontWeight.regular, - ), - ), - ], - ), - SizedBox( - height: 7.h, - ), - Row( - children: [ - Expanded( - child: Text( - messageContent(lastMessageMap[conversationId]!), - maxLines: 1, - overflow: TextOverflow.ellipsis, + Text( + lastMessageMap[conversationId]?.time != null + ? AppUtils.timeFormatter( + DateTime.fromMillisecondsSinceEpoch(int.parse( + lastMessageMap[conversationId]?.time ?? ""))) + : "", style: TextStyle( fontSize: 12.sp, - color: Color(0xFF353535), + color: Color(0xFFA29E9E), fontWeight: MyFontWeight.regular, ), ), - ), - if (unreadCountMap[conversationId] != null && - unreadCountMap[conversationId]! > 0) - Container( - width: 16, - height: 16, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(100), - color: Color(0xFFFF441A), - ), - child: RoundButton( - text: "${unreadCountMap[conversationId]}", - textColor: Colors.white, - fontWeight: MyFontWeight.regular, - backgroup: Color(0xFFFF441A), - fontSize: 10.sp, - radius: 100, + ], + ), + SizedBox( + height: 7.h, + ), + Row( + children: [ + Expanded( + child: Text( + messageContent(lastMessageMap[conversationId]!), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.sp, + color: Color(0xFF353535), + fontWeight: MyFontWeight.regular, + ), ), ), - ], - ), - ], + if (unreadCountMap[conversationId] != null && + unreadCountMap[conversationId]! > 0) + Container( + width: 16, + height: 16, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(100), + color: Color(0xFFFF441A), + ), + child: RoundButton( + text: "${unreadCountMap[conversationId]}", + textColor: Colors.white, + fontWeight: MyFontWeight.regular, + backgroup: Color(0xFFFF441A), + fontSize: 10.sp, + radius: 100, + ), + ), + ], + ), + ], + ), ), - ), - ], + ], + ), ), ); } diff --git a/lib/im/im_view/on_chat_msg_instance.dart b/lib/im/im_view/on_chat_msg_instance.dart index f9edb6c4..a9a5c643 100644 --- a/lib/im/im_view/on_chat_msg_instance.dart +++ b/lib/im/im_view/on_chat_msg_instance.dart @@ -1,20 +1,20 @@ import 'on_chat_message.dart'; -class OnChatMsgInstance{ - factory OnChatMsgInstance() => _getInstance(); - - static OnChatMsgInstance get instance => _getInstance(); - - static OnChatMsgInstance? _instance; - - OnChatMessage? onChatMessage; - - OnChatMsgInstance._internal(); - - static OnChatMsgInstance _getInstance(){ - if(_instance == null){ - _instance = OnChatMsgInstance._internal(); - } - return _instance!; - } -} \ No newline at end of file +// class OnChatMsgInstance{ +// factory OnChatMsgInstance() => _getInstance(); +// +// static OnChatMsgInstance get instance => _getInstance(); +// +// static OnChatMsgInstance? _instance; +// +// OnChatMessage? onChatMessage; +// +// OnChatMsgInstance._internal(); +// +// static OnChatMsgInstance _getInstance(){ +// if(_instance == null){ +// _instance = OnChatMsgInstance._internal(); +// } +// return _instance!; +// } +// } \ No newline at end of file diff --git a/lib/integral/integral_detailed_page.dart b/lib/integral/integral_detailed_page.dart index f5132e5b..ee33bd8b 100644 --- a/lib/integral/integral_detailed_page.dart +++ b/lib/integral/integral_detailed_page.dart @@ -9,14 +9,15 @@ import 'package:huixiang/data/user_bill.dart'; import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_tab.dart'; +import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; -import '../view_widget/no_data_view.dart'; class IntegralDetailedPage extends StatefulWidget { final arguments; @@ -70,25 +71,28 @@ class _IntegralDetailedPage extends State @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, token: value.getString("token")), - userInfo = UserInfo.fromJson(jsonDecode(value.getString('user') ?? "")), - queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_get", widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_ADD" :""), - }); + apiService = ApiService(Dio(), + context: context, token: SharedInstance.instance.token); + userInfo = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)); + queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_get", + widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_ADD" :""); } queryDetail(category,type) async { BaseData>? baseData = await apiService?.queryBillInfo({ "current": current, - "model": {"category": category, "title": widget.arguments["titleType"] == 1 ? "":"bill_title_point", "type": type}, + "model": { + "category": category, + "title": widget.arguments["titleType"] == 1 ? "":"bill_title_point", + "type": type, + }, "order": "descending", "size": 10, "sort": "id" }).catchError((onError) { refreshController.loadFailed(); refreshController.refreshFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); if (current == 1) userBill.clear(); if (baseData?.isSuccess ?? false) { @@ -127,6 +131,7 @@ class _IntegralDetailedPage extends State @override Widget build(BuildContext context) { + super.build(context); return Scaffold( body: NestedScrollView( headerSliverBuilder: (context, inner) { @@ -181,14 +186,16 @@ class _IntegralDetailedPage extends State style: TextStyle( color: Colors.white, fontWeight: MyFontWeight.medium, - fontSize: 48.sp), + fontSize: 48.sp, + ), ), Text( widget.arguments["titleType"] == 1 ? "我的印章" : S.of(context).wodejifenzhi, style: TextStyle( color: Color(0xFFF2F2F2), fontSize: 12.sp, - fontWeight: MyFontWeight.regular), + fontWeight: MyFontWeight.regular, + ), ), ], ), @@ -211,13 +218,18 @@ class _IntegralDetailedPage extends State indicatorSize: TabBarIndicatorSize.label, labelColor: Colors.white, labelStyle: TextStyle( - fontSize: 16.sp, fontWeight: MyFontWeight.medium), + fontSize: 16.sp, + fontWeight: MyFontWeight.medium, + ), unselectedLabelStyle: TextStyle( - fontSize: 16.sp, fontWeight: MyFontWeight.medium), + fontSize: 16.sp, + fontWeight: MyFontWeight.medium, + ), indicatorColor: Colors.white, unselectedLabelColor: Color(0xFFE6E6E6), ), - )), + ), + ), ), ]; }, @@ -238,13 +250,14 @@ class _IntegralDetailedPage extends State onLoading: _loadMore, child: (userBill.length == 0) ? NoDataView( - src: "assets/image/xiao_fei.webp", - isShowBtn: false, - text: "当前暂无记录哦~", - fontSize: 16.sp, - margin: EdgeInsets.all(60.h), - ):ListView.builder( - itemCount: userBill != null ? userBill.length : 0, + src: "assets/image/xiao_fei.webp", + isShowBtn: false, + text: "当前暂无记录哦~", + fontSize: 16.sp, + margin: EdgeInsets.all(60.h), + ) + : ListView.builder( + itemCount: userBill.length, padding: EdgeInsets.only(top: 8, bottom: 8), itemBuilder: (context, position) { return Container( @@ -259,8 +272,9 @@ class _IntegralDetailedPage extends State offset: Offset(0, 2), blurRadius: 3, spreadRadius: 0, - ) - ]), + ), + ], + ), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, @@ -273,25 +287,29 @@ class _IntegralDetailedPage extends State mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Padding(padding: EdgeInsets.only(bottom: 8.h), + Padding( + padding: EdgeInsets.only(bottom: 8.h), child: Text( userBill[position].type ?? "", // S.of(context).qiandao, style: TextStyle( color: Colors.black, fontSize: 14.sp, - fontWeight: FontWeight.bold), + fontWeight: FontWeight.bold, + ), ),), Text( userBill[position].createTime ?? "", style: TextStyle( color: Color(0xFF4D4D4D), fontSize: 12.sp, - fontWeight: MyFontWeight.regular), - ) + fontWeight: MyFontWeight.regular, + ), + ), ], ), - )), + ), + ), Container( margin: EdgeInsets.only(top: 2.h), child: Text( @@ -300,61 +318,12 @@ class _IntegralDetailedPage extends State color: Color(0xFF4D4D4D), fontSize: 14.sp, fontFamily: 'JDZhengHT', - fontWeight: MyFontWeight.regular), + fontWeight: MyFontWeight.regular, + ), ), - ) + ), ], - ) - // Row( - // mainAxisAlignment: MainAxisAlignment.start, - // crossAxisAlignment: CrossAxisAlignment.center, - // children: [ - // Image.asset( - // "assets/image/icon_intergral_sign.webp", - // width: 36.w, - // height: 34.h, - // ), - // SizedBox( - // width: 15, - // ), - // Expanded( - // child: Container( - // // height: 34.h, - // alignment: Alignment.centerLeft, - // child: Column( - // mainAxisAlignment: MainAxisAlignment.spaceAround, - // crossAxisAlignment: CrossAxisAlignment.start, - // children: [ - // Text( - // userBill[position].type ?? "", - // // S.of(context).qiandao, - // style: TextStyle( - // color: Colors.black, - // fontSize: 12.sp, - // fontWeight: FontWeight.w400), - // ), - // Text( - // userBill[position].createTime ?? "", - // style: TextStyle( - // color: Color(0xFF727272), - // fontSize: 10.sp, - // fontWeight: MyFontWeight.regular), - // ) - // ], - // ), - // )), - // Container( - // margin: EdgeInsets.only(top: 2.h), - // child: Text( - // "${tabController.index == 0 ? "+" : "-"}${double.tryParse(userBill[position].number ?? "0").toInt().toString()}", - // style: TextStyle( - // color: Color(0xFF727272), - // fontSize: 12.sp, - // fontWeight: MyFontWeight.regular), - // ), - // ) - // ], - // ), + ), ); }, ), diff --git a/lib/integral/integral_page.dart b/lib/integral/integral_page.dart index 2e297893..908a2713 100644 --- a/lib/integral/integral_page.dart +++ b/lib/integral/integral_page.dart @@ -15,6 +15,7 @@ import 'package:huixiang/integral/intergra_view/in_for_points.dart'; import 'package:huixiang/integral/intergra_view/integral_vip.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -43,22 +44,17 @@ class _IntegralPage extends State { final RefreshController refreshController = RefreshController(); querySignInfo() async { - // SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai); - - SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService( Dio(), context: context, - token: value.getString("token"), + token: SharedInstance.instance.token, showLoading: false, ); - userInfo = UserInfo.fromJson(jsonDecode(value.getString("user") ?? "")); + userInfo = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)); - BaseListData? rankData = - await apiService?.rankList().catchError((onError) { - SmartDialog.showToast(AppUtils.dioErrorTypeToString(onError.type), - alignment: Alignment.center); + BaseListData? rankData = await apiService?.rankList().catchError((onError) { refreshController.refreshFailed(); + return BaseListData()..isSuccess = false; }); if (rankData?.isSuccess ?? false) { ranks.clear(); @@ -69,13 +65,12 @@ class _IntegralPage extends State { } if (ranks.length > 0) { - rankLevel = (ranks.indexWhere( - (element) => element.id == userInfo?.memberRankVo?.id) + - 1); + rankLevel = (ranks.indexWhere((element) => element.id == userInfo?.memberRankVo?.id) + 1); } - BaseData? baseData = - await apiService?.signInInfo().catchError((onError) {}); + BaseData? baseData = await apiService?.signInInfo().catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { signInfo = baseData!.data; refreshController.refreshCompleted(); @@ -89,20 +84,6 @@ class _IntegralPage extends State { color: Colors.white, child: Stack( children: [ - // Positioned( - // child: Container( - // height: 122.h + kToolbarHeight + MediaQuery.of(context).padding.top, - // decoration: BoxDecoration( - // image: DecorationImage( - // fit: BoxFit.fill, - // image: AssetImage("assets/image/jifen.webp"), - // ), - // ), - // ), - // top: 0, - // left: 0, - // right: 0, - // ), Container( decoration: BoxDecoration( image: DecorationImage( @@ -186,7 +167,8 @@ class _IntegralPage extends State { 0] ?? 0) : 0) - .toString()), + .toString(), + ), ///立即签到 InForPoints(signInfo, _signIn), @@ -215,13 +197,17 @@ class _IntegralPage extends State { SmartDialog.showLoading( msg: S.of(context).zhengzaijiazai, ); - BaseData? baseData = await apiService?.signIn().catchError((onError) {}); + BaseData? baseData = await apiService?.signIn().catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() {}); SmartDialog.show( builder: (ctx) => SignInWidget( - "${(signInfo?.signInList?.length ?? 0) + 1}", - "${signInfo?.rewardList?[(signInfo?.signInList?.length ?? 0)]}")); + "${(signInfo?.signInList?.length ?? 0) + 1}", + "${signInfo?.rewardList?[(signInfo?.signInList?.length ?? 0)]}", + ), + ); } else { SmartDialog.dismiss(); } diff --git a/lib/integral/intergra_view/integral_vip.dart b/lib/integral/intergra_view/integral_vip.dart index 12d82e0c..2d78eb19 100644 --- a/lib/integral/intergra_view/integral_vip.dart +++ b/lib/integral/intergra_view/integral_vip.dart @@ -24,12 +24,13 @@ class IntegralVip extends StatefulWidget { } - class _IntegralVip extends State { @override Widget build(BuildContext context) { return Container( - padding: EdgeInsets.symmetric(vertical: 16.h,horizontal: 16.w), + padding: EdgeInsets.symmetric( + vertical: 16.h,horizontal: 16.w, + ), child: Row( children: [ MImage( @@ -96,52 +97,6 @@ class _IntegralVip extends State { ], ), ), - // Container( - // width: 2.w, - // height: 32.h, - // color: Color(0xFFFFFFFF), - // ), - // Expanded( - // flex: 1, - // child: Column( - // mainAxisAlignment: MainAxisAlignment.center, - // crossAxisAlignment: CrossAxisAlignment.center, - // children: [ - // Text( - // (widget?.signInfo?.rank?.rankName != null) - // ? "${widget.signInfo.rank.rankName.replaceAll("会员", "")}" - // : "", - // style: TextStyle( - // fontWeight: MyFontWeight.medium, - // fontSize: 21.sp, - // color: Colors.white, - // ), - // ), - // SizedBox( - // height: 6.h, - // ), - // Row( - // mainAxisAlignment: MainAxisAlignment.center, - // crossAxisAlignment: CrossAxisAlignment.center, - // children: [ - // Text( - // S.of(context).wodehuiyuandengji, - // style: TextStyle( - // fontSize: 12.sp, - // fontWeight: MyFontWeight.regular, - // color: Color(0xFFF2F2F2), - // ), - // ), - // // Icon( - // // Icons.keyboard_arrow_right, - // // color: Colors.white, - // // size: 15, - // // ), - // ], - // ), - // ], - // ), - // ), ], ), ); diff --git a/lib/integral_store/integral_store_details_page.dart b/lib/integral_store/integral_store_details_page.dart index b0189b0a..0a091a0c 100644 --- a/lib/integral_store/integral_store_details_page.dart +++ b/lib/integral_store/integral_store_details_page.dart @@ -12,6 +12,7 @@ import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -42,15 +43,12 @@ class _IntegralStoreDetailsPage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), context: context, token: value.getString("token")); - queryGoodsById(); - if (value.getString('user') != null) { - points = UserInfo.fromJson(jsonDecode(value.getString('user')!)).points; - happyBean = UserInfo.fromJson(jsonDecode(value.getString('user')!)).happyBean; - } - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryGoodsById(); + if (SharedInstance.instance.userJson.isNotEmpty) { + points = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)).points; + happyBean = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)).happyBean; + } } Goods? goods; @@ -58,7 +56,9 @@ class _IntegralStoreDetailsPage extends State { ///查询积分商品详情 queryGoodsById() async { BaseData? baseData = await apiService?.creditGoodsById(widget.arguments?["goodsId"] ?? "") - .catchError((onError) {}); + .catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { goods = baseData?.data; @@ -77,7 +77,7 @@ class _IntegralStoreDetailsPage extends State { } refreshController.refreshCompleted(); }); - }else { + } else { refreshController.refreshFailed(); } } @@ -175,9 +175,7 @@ class _IntegralStoreDetailsPage extends State { color: (payType > 0) ? Color(0xFF32A060) : Color(0xFFD8D8D8), - borderRadius: BorderRadius.circular( - 45 - ), + borderRadius: BorderRadius.circular(45), ), alignment: Alignment.center, child: Text( @@ -200,25 +198,27 @@ class _IntegralStoreDetailsPage extends State { //1-配送,2-自提,3-虚拟 toExchangeOrder() async { - await Navigator.of(context) - .pushNamed('/router/exchange_order_page', arguments: { - "goodsId": goods?.id, - "name": goods?.name, - "money": goods?.money, - "onePrice":goods?.onePrice, - "oneMoney":goods?.oneMoney, - "oneBean":goods?.oneBean, - "price": goods?.price, - "image": goods?.mainImgPath, - "payType":payType, - "useTyped": (goods?.canPick ?? false) - ? 1 - : (goods?.canDelivery ?? false) - ? 2 - : 3, - }); - var shared = await SharedPreferences.getInstance(); - points = UserInfo.fromJson(jsonDecode(shared.getString('user') ?? "")).points; + await Navigator.of(context).pushNamed( + '/router/exchange_order_page', + arguments: { + "goodsId": goods?.id, + "name": goods?.name, + "money": goods?.money, + "onePrice":goods?.onePrice, + "oneMoney":goods?.oneMoney, + "oneBean":goods?.oneBean, + "price": goods?.price, + "image": goods?.mainImgPath, + "payType":payType, + "useTyped": (goods?.canPick ?? false) + ? 1 + : (goods?.canDelivery ?? false) + ? 2 + : 3, + }, + ); + + points = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)).points; setState(() {}); } diff --git a/lib/login/captcha/block_puzzle_captcha.dart b/lib/login/captcha/block_puzzle_captcha.dart index a37317d5..020f01fe 100644 --- a/lib/login/captcha/block_puzzle_captcha.dart +++ b/lib/login/captcha/block_puzzle_captcha.dart @@ -151,7 +151,9 @@ class _BlockPuzzleCaptchaPageState extends State ApiService apiIpService = ApiService(Dio(), context: context); CaptchaData baseData = await apiIpService.captchaGet({ "captchaType": "blockPuzzle", - }).catchError((onError) {}); + }).catchError((onError) { + return CaptchaData(); + }); debugPrint("ClickWordCaptchaModel: ${baseData.toJson()}"); diff --git a/lib/login/login_page.dart b/lib/login/login_page.dart index 21eb6a59..a9f6c1fd 100644 --- a/lib/login/login_page.dart +++ b/lib/login/login_page.dart @@ -17,6 +17,7 @@ import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/round_button.dart'; import 'package:photo_view/photo_view.dart'; @@ -62,16 +63,10 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { String? areaCode; isLogin() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - - if (sharedPreferences.getBool("isShowPrivacyPolicy") == null || - !(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) { + if (!SharedInstance.instance.isShowPrivacyPolicy) { showAlertDialog(); } - - if (sharedPreferences.containsKey('token') && - sharedPreferences.getString("token") != null && - sharedPreferences.getString("token") != "") { + if (SharedInstance.instance.token.isNotEmpty) { Navigator.of(context).popAndPushNamed('/router/main_page'); } else { initController(); @@ -133,8 +128,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { changeAlpha = (offset / (height - chaHeight) * (255)).toInt(); changeAlpha = (changeAlpha > 255 ? 255 : changeAlpha); changeAlpha = (changeAlpha < 0 ? 0 : changeAlpha); - alpha = (initAlpha + offset / (height - chaHeight) * (255 - initAlpha)) - .toInt(); + alpha = (initAlpha + offset / (height - chaHeight) * (255 - initAlpha)).toInt(); alpha = (alpha > 255 ? 255 : alpha); alpha = (alpha < 0 ? 0 : alpha); }); @@ -204,9 +198,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { Color statusInviteLineColor = Color(0xFF32A060); _sendCode() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - if (!sharedPreferences.containsKey("isShowPrivacyPolicy") || - !(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) { + if (!SharedInstance.instance.isShowPrivacyPolicy) { showAlertDialog(); return; } @@ -223,10 +215,12 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { return; } if (_sendCodeStatus == 0) { - client - ?.sendVerify( - {"areaCode": areaCode, "mobile": mobile, "verification": ""}) - .then((value) => { + client?.sendVerify({ + "areaCode": areaCode, "mobile": mobile, "verification": "", + }).catchError((error) { + SmartDialog.showToast("$error", alignment: Alignment.center); + return BaseData()..isSuccess = false; + }).then((value) => { if (value.isSuccess ?? false) {_sendCodeStatus = 1, countdown()} else @@ -237,11 +231,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { alignment: Alignment.center), refresh() } - }) - .catchError((error) { - SmartDialog.showToast("$error", alignment: Alignment.center); - return Future.value(null); - }); + }); } } @@ -279,9 +269,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { scrollToTop(); return; } - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - if (!sharedPreferences.containsKey("isShowPrivacyPolicy") || - !(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) { + if (!SharedInstance.instance.isShowPrivacyPolicy) { showAlertDialog(); return; } @@ -327,12 +315,9 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { SmartDialog.showLoading( msg: S.of(context).zhengzaijiazai, ); - BaseData? value = - await client?.memberLogin(param).catchError((error) { + BaseData? value = await client?.memberLogin(param).catchError((error) { print(error.message); - SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type), - alignment: Alignment.center); - return Future.value(null); + return BaseData()..isSuccess = false; }); // SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai); Future.delayed(Duration(seconds: 2), () { @@ -346,7 +331,8 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { "invite": invite, "interviewCouponList": value.data?.interviewCouponList, "firstLoginCouponList": value.data?.firstLoginCouponList - }); + }, + ); SmartDialog.dismiss(); } else { SmartDialog.showToast("${value?.msg}", alignment: Alignment.center); @@ -356,13 +342,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { saveUserJson(userJson) { var userEntity = UserEntity.fromJson(userJson); - SharedPreferences.getInstance().then((value) => { - value.setString('userJson', jsonEncode(userJson)), - value.setString('token', "${userEntity.token}"), - value.setString('userId', "${userEntity.userId}"), - value.setString('nick', "${userEntity.name}"), - value.setString('mobile', "${userEntity.mobile}"), - }); + SharedInstance.instance.saveUserInfo(userEntity); } late AnimationController animatedContainer; @@ -402,8 +382,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { } animationStart() { - animatedContainer = - AnimationController(vsync: this, duration: Duration(seconds: 10)); + animatedContainer = AnimationController(vsync: this, duration: Duration(seconds: 10)); animation = AlignmentTween(begin: alignmentBegin, end: alignmentEnd) .animate(animatedContainer); @@ -458,8 +437,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { secondChild: uiPage(), firstCurve: Curves.easeInQuart, secondCurve: Curves.easeInQuart, - crossFadeState: - isShowLogin ? CrossFadeState.showSecond : CrossFadeState.showFirst, + crossFadeState: isShowLogin ? CrossFadeState.showSecond : CrossFadeState.showFirst, duration: Duration(milliseconds: Platform.isIOS ? 1000 : 1000), ); } @@ -1052,21 +1030,19 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { ), SizedBox( height: 208.h, - ) + ), ], ), ); } scrollToTop() { - RenderBox? renderBox = - loginKey.currentContext?.findRenderObject() as RenderBox?; + RenderBox? renderBox = loginKey.currentContext?.findRenderObject() as RenderBox?; var screenHeight = MediaQuery.of(context).size.height; var scrollHeight = screenHeight * 1.47; var height = scrollHeight - (renderBox?.size.height ?? 0); var chaHeight = screenHeight - (renderBox?.size.height ?? 0); - scrollController?.animateTo(height - chaHeight, - duration: Duration(milliseconds: 500), curve: Curves.ease); + scrollController?.animateTo(height - chaHeight, duration: Duration(milliseconds: 500), curve: Curves.ease); } showAlertDialog() { @@ -1108,29 +1084,30 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { ), ), Text.rich( - TextSpan(children: [ - TextSpan( - text: S.of(context).yinsizhengce1, - style: TextStyle( - fontWeight: MyFontWeight.medium, - fontSize: 14.sp, - height: 1.2.h, - color: Color(0xff727272), - ), - ), - TextSpan( - text: S.of(context).yinsixieyi, - style: TextStyle( + TextSpan( + children: [ + TextSpan( + text: S.of(context).yinsizhengce1, + style: TextStyle( fontWeight: MyFontWeight.medium, fontSize: 14.sp, - color: Color(0xff32A060)), - recognizer: TapGestureRecognizer() - ..onTap = () { - Navigator.of(context) - .popAndPushNamed('/router/treaty_page'); - }, - ), - ]), + height: 1.2.h, + color: Color(0xff727272), + ), + ), + TextSpan( + text: S.of(context).yinsixieyi, + style: TextStyle( + fontWeight: MyFontWeight.medium, + fontSize: 14.sp, + color: Color(0xff32A060)), + recognizer: TapGestureRecognizer() + ..onTap = () { + Navigator.of(context).popAndPushNamed('/router/treaty_page'); + }, + ), + ], + ), ), SizedBox( height: 5.h, @@ -1191,9 +1168,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { textColor: Colors.white, fontSize: 12.sp, callback: () { - SharedPreferences.getInstance().then((value) { - value.setBool("isShowPrivacyPolicy", true); - }); + SharedInstance.instance.showPrivacyPolicy(); SharesdkPlugin.uploadPrivacyPermissionStatus( 1, (success) => { @@ -1217,7 +1192,7 @@ class _MyLoginPageState extends State with TickerProviderStateMixin { ], ), ], - ) + ), ], ); }, diff --git a/lib/login/new_login_page.dart b/lib/login/new_login_page.dart index 10fb63be..2c5a38f0 100644 --- a/lib/login/new_login_page.dart +++ b/lib/login/new_login_page.dart @@ -8,21 +8,23 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:get/get.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/channels.dart'; import 'package:huixiang/data/examine_instance.dart'; import 'package:huixiang/data/user_entity.dart'; import 'package:huixiang/generated/l10n.dart'; +import 'package:huixiang/main.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/round_button.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sharesdk_plugin/sharesdk_interface.dart'; -import '../main.dart'; import 'captcha/block_puzzle_captcha.dart'; class NewLoginPage extends StatefulWidget { @@ -63,18 +65,12 @@ class _NewLoginPage extends State { } queryChannels() async { - BaseData? baseData = - await apiService?.appChannels().catchError((error) { - print(error.message); - SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type), - alignment: Alignment.center); + BaseData? baseData = await apiService?.appChannels().catchError((error) { return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { channelsList = baseData!.data; setState(() {}); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -121,9 +117,7 @@ class _NewLoginPage extends State { } _sendCode() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - if (!sharedPreferences.containsKey("isShowPrivacyPolicy") || - !(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) { + if (!SharedInstance.instance.isShowPrivacyPolicy) { showAlertDialog(); return; } @@ -131,14 +125,18 @@ class _NewLoginPage extends State { if (mobile == "") { mobileStatus = 2; mobileErrorText = S.of(context).qingshurushoujihao; - SmartDialog.showToast(S.of(context).qingshurushoujihao, - alignment: Alignment.center); + SmartDialog.showToast( + S.of(context).qingshurushoujihao, + alignment: Alignment.center, + ); setState(() {}); return; } if (!checkStatus) { - SmartDialog.showToast(S.of(context).gouxuanxieyi, - alignment: Alignment.center); + SmartDialog.showToast( + S.of(context).gouxuanxieyi, + alignment: Alignment.center, + ); return; } if (_sendCodeStatus == 0) { @@ -171,15 +169,15 @@ class _NewLoginPage extends State { } _login() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - if (!sharedPreferences.containsKey("isShowPrivacyPolicy") || - !(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) { + if (!SharedInstance.instance.isShowPrivacyPolicy) { showAlertDialog(); return; } if (!checkStatus) { - SmartDialog.showToast(S.of(context).gouxuanxieyi, - alignment: Alignment.center); + SmartDialog.showToast( + S.of(context).gouxuanxieyi, + alignment: Alignment.center, + ); return; } var mobile = _controllerPhone.text; @@ -189,12 +187,6 @@ class _NewLoginPage extends State { setState(() {}); return; } - // if (mobile.length != 11) { - // mobileStatus = 2; - // mobileErrorText = S.of(context).phone_error; - // setState(() {}); - // return; - // } var code = _controllerCode.text; if (code == "") { @@ -221,16 +213,12 @@ class _NewLoginPage extends State { msg: S.of(context).zhengzaijiazai, ); BaseData? value = await apiService?.memberLogin(param).catchError((error) { - print(error.message); - SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type), - alignment: Alignment.center); - return Future.value(null); + return BaseData()..isSuccess = false; }); // SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai); if (value?.isSuccess ?? false) { var userInfo = value!.data; - ExamineInstance.instance.isExamine = - userInfo.authInfo?.account == "13800138000"; + ExamineInstance.instance.isExamine = userInfo.authInfo?.account == "13800138000"; saveUserJson(userInfo.authInfo?.toJson()); eventBus.fire(EventType(3)); @@ -249,28 +237,20 @@ class _NewLoginPage extends State { saveUserJson(userJson) { var userEntity = UserEntity.fromJson(userJson); - SharedPreferences.getInstance().then((value) => { - value.setString('userJson', jsonEncode(userJson)), - value.setString('token', "${userEntity.token}"), - value.setString('userId', "${userEntity.userId}"), - value.setString('nick', "${userEntity.name}"), - value.setString('mobile', "${userEntity.mobile}"), - }); + SharedInstance.instance.saveUserInfo(userEntity); } isLogin() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - if (sharedPreferences.getBool("isShowPrivacyPolicy") == null || - !(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) { + + if (!SharedInstance.instance.isShowPrivacyPolicy) { showAlertDialog(); } - if (sharedPreferences.containsKey('token') && - sharedPreferences.getString("token") != null && - sharedPreferences.getString("token") != "") { - ExamineInstance.instance.isExamine = - sharedPreferences.getString("mobile") == "13800138000"; - Navigator.of(context).popAndPushNamed('/router/main_page'); + if (SharedInstance.instance.token.isNotEmpty) { + ExamineInstance.instance.isExamine = SharedInstance.instance.mobile == "13800138000"; + WidgetsBinding.instance.addPostFrameCallback((timeStamp) { + Navigator.of(context).popAndPushNamed('/router/main_page'); + }); } else { apiService = ApiService(Dio(), context: context); initController(); @@ -935,9 +915,7 @@ class _NewLoginPage extends State { textColor: Colors.white, fontSize: 12.sp, callback: () { - SharedPreferences.getInstance().then((value) { - value.setBool("isShowPrivacyPolicy", true); - }); + SharedInstance.instance.showPrivacyPolicy(); SharesdkPlugin.uploadPrivacyPermissionStatus( 1, (success) => { diff --git a/lib/main.dart b/lib/main.dart index c9b486c5..49460913 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -79,6 +79,7 @@ import 'package:huixiang/union/union_details_page.dart'; import 'package:huixiang/union/union_select_city.dart'; import 'package:huixiang/utils/ImgCachePath.dart'; import 'package:huixiang/utils/qiniu.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/vip/user_vip_service_page.dart'; import 'package:huixiang/web/web_page.dart'; import 'package:huixiang/web/web_turntable_activity.dart'; @@ -141,7 +142,8 @@ import 'order/invoices_manage/invoices_title_info.dart'; void main() async { if (Platform.isAndroid) { SystemChrome.setSystemUIOverlayStyle( - SystemUiOverlayStyle(statusBarColor: Colors.transparent)); + SystemUiOverlayStyle(statusBarColor: Colors.transparent), + ); } WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations([ @@ -157,24 +159,14 @@ void main() async { locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH'); } ImgCachePath(); - // initSdk(); + bool isFirst = sharedPreferences.getBool("isFirst") ?? true; - initShared(); + SharedInstance.instance.init(sharedPreferences); runApp(MyApp(locale, isFirst)); - // FlutterBugly.postCatchedException((){ - // }); - // FlutterBugly.init(androidAppId: "204f207673",iOSAppId: "8bb92ba0f6"); } -// final XgFlutterPlugin xgFlutterPlugin = XgFlutterPlugin(); - late HxDatabase hxDatabase; -late SharedPreferences sharedPreferences; - -initShared() async { - sharedPreferences = await SharedPreferences.getInstance(); -} initDatabase(String userId) async { hxDatabase = HxDatabase(); @@ -199,87 +191,79 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ScreenUtilInit( - builder: ( - BuildContext context, - Widget? child, - ) => - GetMaterialApp( - debugShowCheckedModeBanner: false, - title: Platform.isAndroid - ? (ExamineInstance.instance.isExamine ? "海峡姐妹" : "") - : "", - theme: ThemeData( - primarySwatch: Colors.blue, - // fontFamily: 'JDZhengHT', - textTheme: TextTheme( - button: TextStyle(fontSize: 24.sp), - bodyText1: TextStyle(fontSize: 12.sp), - bodyText2: TextStyle(fontSize: 16.sp), + builder: (BuildContext context, Widget? child,) { + return GetMaterialApp( + debugShowCheckedModeBanner: false, + title: Platform.isAndroid + ? (ExamineInstance.instance.isExamine ? "海峡姐妹" : "") + : "", + theme: ThemeData( + primarySwatch: Colors.blue, + // fontFamily: 'JDZhengHT', + brightness: Brightness.light, + textTheme: TextTheme( + labelMedium: TextStyle(fontSize: 16.sp), + labelSmall: TextStyle(fontSize: 16.sp), + labelLarge: TextStyle(fontSize: 16.sp), + ), ), - ), - localeResolutionCallback: (locale, supportedLocales) { - print("locale: $locale"); - print("supportedLocales: $supportedLocales"); - return appLocale ?? locale; - }, - localizationsDelegates: [ - S.delegate, - GlobalMaterialLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - ], - localeListResolutionCallback: - (List? locales, Iterable supportedLocales) { - Locale? locale; - if (locales?.isNotEmpty ?? false) { - print("locale: ${locales![0]}"); - if (locales[0].countryCode == "TW") { - locale = - Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW'); - } else if (locales[0].countryCode == "US") { - locale = - Locale.fromSubtags(languageCode: 'en', countryCode: 'US'); - } else { - locale = - Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH'); + localeResolutionCallback: (locale, supportedLocales) { + print("locale: $locale"); + print("supportedLocales: $supportedLocales"); + return appLocale ?? locale; + }, + localizationsDelegates: [ + S.delegate, + GlobalMaterialLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ], + localeListResolutionCallback: (List? locales, Iterable supportedLocales) { + Locale? locale; + if (locales?.isNotEmpty ?? false) { + print("locale: ${locales![0]}"); + if (locales[0].countryCode == "TW") { + locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW'); + } else if (locales[0].countryCode == "US") { + locale = Locale.fromSubtags(languageCode: 'en', countryCode: 'US'); + } else { + locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH'); + } + } + return appLocale ?? locale ?? Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH'); + }, + supportedLocales: S.delegate.supportedLocales, + home: (isFirst) ? GuidePage() : NewLoginPage(), + // home: StartPage(isFirst), + builder: FlutterSmartDialog.init(), + onGenerateRoute: (settings) { + final String? name = settings.name; + if (lastRoutePage?.settings.name == name) { + if (lastRoutePage?.settings.name == "/router/personal_page" && + lastRoutePage?.navigator != null) + lastRoutePage!.navigator?.pop(); } - } - return appLocale ?? - locale ?? - Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH'); - }, - supportedLocales: S.delegate.supportedLocales, - home: (isFirst) ? GuidePage() : NewLoginPage(), - // home: StartPage(isFirst), - builder: FlutterSmartDialog.init(), - onGenerateRoute: (settings) { - final String? name = settings.name; - if (lastRoutePage?.settings.name == name) { - if (lastRoutePage?.settings.name == "/router/personal_page" && - lastRoutePage?.navigator != null) - lastRoutePage!.navigator?.pop(); - } - final Function? pageContentBuilder = routers[name]; - if (pageContentBuilder != null) { - final Route route = CupertinoPageRoute( + final Function? pageContentBuilder = routers[name]; + if (pageContentBuilder != null) { + final Route route = CupertinoPageRoute( + builder: (context) { + return pageContentBuilder(context, arguments: settings.arguments); + }, + settings: settings, + ); + lastRoutePage = route; + return route; + } + return MaterialPageRoute( + //未找到页面配置进入登录页 builder: (context) { - return pageContentBuilder(context, - arguments: settings.arguments); + return NewLoginPage(); }, settings: settings, ); - lastRoutePage = route; - return route; - } - return MaterialPageRoute( - //未找到页面配置进入登录页 - builder: (context) { - return NewLoginPage(); - }, - settings: settings, - ); - }, - ), + }, + ); + }, ); } } diff --git a/lib/main_page.dart b/lib/main_page.dart index af41b095..01b9163e 100644 --- a/lib/main_page.dart +++ b/lib/main_page.dart @@ -23,10 +23,10 @@ import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/utils/native_event_handler.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/update_dialog.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:permission_handler/permission_handler.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:sharesdk_plugin/sharesdk_interface.dart'; import 'package:sharesdk_plugin/sharesdk_register.dart'; import 'package:tpns_flutter_plugin/android/xg_android_api.dart'; @@ -102,11 +102,9 @@ class _MainPage extends State with WidgetsBindingObserver { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - String userId = value.getString("userId") ?? ""; - initDatabase(userId); - connectSocket(); - }); + String userId = SharedInstance.instance.userId; + initDatabase(userId); + connectSocket(); pageController = PageController( initialPage: @@ -268,9 +266,7 @@ class _MainPage extends State with WidgetsBindingObserver { MyNativeEventHandler( (String title, String message, String customContent, int type) { print("xgPushClickAction2: $customContent"); - SharedPreferences.getInstance().then((value) { - value.setString("pushData", customContent); - }); + SharedInstance.instance.savePushData(pushData: customContent); }, ), ); @@ -291,16 +287,14 @@ class _MainPage extends State with WidgetsBindingObserver { ? (event["actionType"] == 0) : (event["xg"]["msgtype"] == 1) && event[Platform.isAndroid ? "customMessage" : "custom"] != null) { - SharedPreferences.getInstance().then((value) { - value.setString("pushData", - event[Platform.isAndroid ? "customMessage" : "custom"]); - }); + SharedInstance.instance.savePushData(pushData: event[Platform.isAndroid ? "customMessage" : "custom"]); if ((ModalRoute.of(context)?.isActive ?? false) && (ModalRoute.of(context)?.isCurrent ?? false)) { pushRoute(); } else { - Navigator.of(context) - .pushNamedAndRemoveUntil('/router/main_page', (route) => false); + Navigator.of(context).pushNamedAndRemoveUntil( + '/router/main_page', (route) => false, + ); } } return event; @@ -329,9 +323,7 @@ class _MainPage extends State with WidgetsBindingObserver { } pushRoute() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - if (sharedPreferences.getString("token") == null || - sharedPreferences.getString("token") == "") return; + if (SharedInstance.instance.token.isEmpty) return; String? startIntent; if (Platform.isAndroid) startIntent = await Bridge.getStartIntent(); print("intent:${startIntent ?? ''}"); @@ -340,7 +332,7 @@ class _MainPage extends State with WidgetsBindingObserver { pushData = startIntent; // pushData = """{"typed":1,"info":"1420304936817655808"}"""; } else { - pushData = sharedPreferences.getString("pushData") ?? ""; + pushData = SharedInstance.instance.pushData; } if (pushData == "") return; Map? pushMap = jsonDecode(pushData); @@ -401,7 +393,7 @@ class _MainPage extends State with WidgetsBindingObserver { params["id"] = pushMap["info"]; break; } - sharedPreferences.setString("pushData", ""); + SharedInstance.instance.savePushData(); print("xgPushClickAction: routeName: $routeName"); if (routeName != "") { Navigator.of(context).pushNamed(routeName, arguments: params); @@ -410,25 +402,25 @@ class _MainPage extends State with WidgetsBindingObserver { } queryUserInfo() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - if (sharedPreferences.getString("token") == null || - sharedPreferences.getString("token") == "") return; - BaseData baseDate = await ApiService( + if (SharedInstance.instance.token.isEmpty) return; + BaseData? baseDate = await ApiService( Dio(), context: context, - token: sharedPreferences.getString('token'), - ).queryInfo().catchError((onError) {}); - sharedPreferences.setString('user', jsonEncode(baseDate.data)); - - //用户登录时,注册推送的标识是手机号 - String? mobile = baseDate.data?.phone; - if (mobile != null && mobile != "") { - xgFlutterPlugin.setAccount(mobile, AccountType.PHONE_NUMBER); - // xgFlutterPlugin.unbindWithIdentifier(identify: mobile, bindType: XGBindType.account) - xgFlutterPlugin.bindWithIdentifier( - identify: mobile, - bindType: XGBindType.account, - ); + token: SharedInstance.instance.token, + ).queryInfo().catchError((onError) { + return BaseData()..isSuccess = false; + }); + if ((baseDate?.isSuccess ?? false) && baseDate?.data != null) { + SharedInstance.instance.saveUser(baseDate!.data!); + //用户登录时,注册推送的标识是手机号 + String? mobile = baseDate.data?.phone; + if (mobile != null && mobile != "") { + xgFlutterPlugin.setAccount(mobile, AccountType.PHONE_NUMBER); + xgFlutterPlugin.bindWithIdentifier( + identify: mobile, + bindType: XGBindType.account, + ); + } } } @@ -440,24 +432,23 @@ class _MainPage extends State with WidgetsBindingObserver { ///app自动更新 appAutoUpdate() async { - SharedPreferences value = await SharedPreferences.getInstance(); - if (apiService == null) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); PackageInfo packageInfo = await PackageInfo.fromPlatform(); - BaseData? baseData = - await apiService?.appVersion().catchError((onError) {}); + BaseData? baseData = await apiService?.appVersion().catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { - // baseData.data.appLastVersion = "2.0.17"; - // baseData.data.appLastVersionUp = "1.0.1"; if (AppUtils.versionCompare( - packageInfo.version, "${baseData?.data?.appLastVersion}") && - AppUtils.versionCompare(value.getString("appLastVersion") ?? "1.0.0", - "${baseData?.data?.appLastVersion}")) { + packageInfo.version, + "${baseData?.data?.appLastVersion}", + ) && AppUtils.versionCompare( + SharedInstance.instance.appLastVersion ?? "1.0.0", + "${baseData?.data?.appLastVersion}", + )) { showDialog( context: context, barrierDismissible: false, @@ -475,7 +466,10 @@ class _MainPage extends State with WidgetsBindingObserver { } } else { if (baseData?.msg?.isNotEmpty ?? false) { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); + SmartDialog.showToast( + "${baseData?.msg}", + alignment: Alignment.center, + ); } Navigator.of(context).pop(); } diff --git a/lib/message/main_message_page.dart b/lib/message/main_message_page.dart index 11603d28..1ea20509 100644 --- a/lib/message/main_message_page.dart +++ b/lib/message/main_message_page.dart @@ -12,15 +12,13 @@ class MainMessagePage extends StatefulWidget { } } -class _MainMessagePage extends State - with SingleTickerProviderStateMixin { - var tabcontroller; +class _MainMessagePage extends State with SingleTickerProviderStateMixin { + @override void initState() { super.initState(); - if (tabcontroller == null) - tabcontroller = TabController(length: 2, vsync: this); + } @override diff --git a/lib/message/real_time_info_page.dart b/lib/message/real_time_info_page.dart index 8cd4b578..61cdcb5f 100644 --- a/lib/message/real_time_info_page.dart +++ b/lib/message/real_time_info_page.dart @@ -17,7 +17,8 @@ class _RealTimeInfoPage extends State { itemBuilder: (context, position) { return Container( margin: EdgeInsets.only( - left: 16, right: 16, top: position == 0 ? 32 : 8, bottom: 8), + left: 16, right: 16, top: position == 0 ? 32 : 8, bottom: 8, + ), padding: EdgeInsets.only(top: 16, bottom: 16), decoration: BoxDecoration( color: Colors.white, @@ -26,12 +27,17 @@ class _RealTimeInfoPage extends State { color: Colors.black.withAlpha(12), offset: Offset(0, 3), blurRadius: 14, - spreadRadius: 0) + spreadRadius: 0, + ), ], - borderRadius: BorderRadius.all(Radius.circular(8))), + borderRadius: BorderRadius.all( + Radius.circular(8), + ), + ), child: MessageItem(0), ); - }), + }, + ), ); } } diff --git a/lib/message/system_details.dart b/lib/message/system_details.dart index 9521ddf1..99526866 100644 --- a/lib/message/system_details.dart +++ b/lib/message/system_details.dart @@ -9,6 +9,7 @@ import 'package:huixiang/data/message.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -50,11 +51,12 @@ class _SystemDetails extends State { super.initState(); msgType = widget.arguments?["msgType"] ?? 0; - SharedPreferences.getInstance().then((value) { - apiService = ApiService(Dio(), - token: value.getString("token"), showLoading: true, context: context); - queryMessage(); - }); + apiService = ApiService(Dio(), + token: SharedInstance.instance.token, + showLoading: true, + context: context, + ); + queryMessage(); } _refresh() { @@ -72,6 +74,7 @@ class _SystemDetails extends State { }).catchError((onError) { _refreshController.loadFailed(); _refreshController.refreshFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (pageNum == 1) { @@ -98,10 +101,10 @@ class _SystemDetails extends State { if (baseData?.isSuccess ?? false) { // widget.refresh(); queryMessage(); - SmartDialog.showToast(isFollow ? "取关成功" : "关注成功", - alignment: Alignment.center); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); + SmartDialog.showToast( + isFollow ? "取关成功" : "关注成功", + alignment: Alignment.center, + ); } } @@ -120,14 +123,14 @@ class _SystemDetails extends State { "parentId": messageRelational["additionId"].toString(), "relationalId": messageRelational["businessId"].toString(), "relationalType": 4 - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { commentTextController.text = ""; FocusScope.of(context).unfocus(); Navigator.of(context).pop(); SmartDialog.showToast("发布成功", alignment: Alignment.center); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } diff --git a/lib/message/system_message.dart b/lib/message/system_message.dart index cd965e92..34735efc 100644 --- a/lib/message/system_message.dart +++ b/lib/message/system_message.dart @@ -10,6 +10,7 @@ import 'package:huixiang/data/page.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; @@ -41,13 +42,10 @@ class _SystemMessagePage extends State { @override void initState() { super.initState(); - - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), token: value.getString("token"), context: context); - queryMessage(); - queryMsgStats(); - }); + apiService = + ApiService(Dio(), token: SharedInstance.instance.token, context: context); + queryMessage(); + queryMsgStats(); } _refresh() { @@ -66,6 +64,7 @@ class _SystemMessagePage extends State { }).catchError((onError) { _refreshController.loadFailed(); _refreshController.refreshFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -94,8 +93,7 @@ class _SystemMessagePage extends State { } queryMsgStats() async { - BaseListData? baseData = - await apiService?.stats().catchError((onError) { + BaseListData? baseData = await apiService?.stats().catchError((onError) { return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -120,35 +118,59 @@ class _SystemMessagePage extends State { @override Widget build(BuildContext context) { return Scaffold( - // appBar: MyAppBar( - // background: Colors.white, - // leadingColor: Colors.black, - // title: S.of(context).xiaoxi, - // titleSize: 18.sp, - // titleColor: Colors.black, - // actions: [ - // Container( - // margin: EdgeInsets.only(right: 16.w), - // alignment: Alignment.centerRight, - // child: GestureDetector( - // onTap: () { - // setState(() { - // queryMsgStats(); - // }); - // }, - // child: Text( - // S.of(context).biaoweiyidu, - // style: TextStyle( - // fontSize: 16.sp, - // fontWeight:MyFontWeight.semi_bold, - // color: Color(0xFF353535), - // ), - // ), - // ), - // ), - // ], - // ), backgroundColor: Colors.white, + appBar: AppBar( + backgroundColor: Colors.white, + surfaceTintColor: Colors.white, + leading: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + Navigator.of(context).pop(); + }, + child: Container( + alignment: Alignment.centerRight, + margin: EdgeInsets.only( + left: 12, + ), + padding: EdgeInsets.all(6), + child: Icon( + Icons.arrow_back_ios, + color: Colors.black, + size: 24, + ), + ), + ), + title: Text( + S.of(context).xiaoxi, + style: TextStyle( + color: Colors.black, + fontSize: 18.sp, + fontWeight: MyFontWeight.bold, + ), + ), + centerTitle: false, + actions: [ + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + setState(() { + queryMsgStats(); + }); + }, + child: Container( + padding: EdgeInsets.symmetric(horizontal: 18), + child: Text( + S.of(context).biaoweiyidu, + style: TextStyle( + color: Colors.black, + fontSize: 16.sp, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ), body: SmartRefresher( enablePullDown: true, enablePullUp: true, @@ -167,136 +189,97 @@ class _SystemMessagePage extends State { _refresh(); }); }, - child: Container( - child: SingleChildScrollView( - physics: BouncingScrollPhysics(), - child: Container( - padding: EdgeInsets.only(bottom: 30.h), - child: Column( - children: [ - Container( - color: Colors.white, - padding: EdgeInsets.only( - top: MediaQuery.of(context).padding.top + 10.h, - bottom: 15.h, - right: 16.w), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - Navigator.of(context).pop(); - }, - child: Container( - alignment: Alignment.centerRight, - margin: EdgeInsets.only( - left: 12, - ), - padding: EdgeInsets.all(6), - child: Icon( - Icons.arrow_back_ios, - color: Colors.black, - size: 24, - ), - ), - ), - Expanded( - child: Text( - S.of(context).xiaoxi, - style: TextStyle( - color: Colors.black, - fontSize: 18.sp, - fontWeight: MyFontWeight.bold, - ), - )), - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - setState(() { - queryMsgStats(); - }); - }, - child: Container( - padding: EdgeInsets.symmetric(horizontal: 10.w), - child: Text( - S.of(context).biaoweiyidu, - style: TextStyle( - color: Colors.black, - fontSize: 16.sp, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - ], - ), - ), - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - Navigator.of(context).pushNamed('/router/system_details', - arguments: {"msgType": 6}).then((value) { - setState(() { - msgNumber["6"] = 0; - }); - }); - }, - child: messageItem("assets/image/icon_pl.webp", - S.of(context).pinglun, msgNumber["6"].toString()), - ), - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - Navigator.of(context).pushNamed('/router/system_details', - arguments: {"msgType": 5}).then((value) { - setState(() { - msgNumber["5"] = 0; - }); - }); - }, - child: messageItem("assets/image/icon_z.webp", - S.of(context).dianzan, msgNumber["5"].toString()), - ), - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - Navigator.of(context).pushNamed('/router/system_details', - arguments: {"msgType": 4}).then((value) { - setState(() { - msgNumber["4"] = 0; - }); - }); - }, - child: messageItem("assets/image/icon_gz.webp", - S.of(context).guanzhu, msgNumber["4"].toString()), - ), - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - Navigator.of(context) - .pushNamed('/router/system_notice') - .then((value) { - setState(() { - msgNumber["2"] = 0; - msgNumber["3"] = 0; - }); - }); - }, - child: messageItem( - "assets/image/icon_system_message.webp", - S.of(context).xitongxiaoxi, - "${(msgNumber["2"] ?? 0) + (msgNumber["3"] ?? 0)}"), - ), - // newsSurvey(), - // SizedBox( - // height: 16.h, - // ), - // buildMessage(), - ], + child: SingleChildScrollView( + physics: BouncingScrollPhysics(), + child: Column( + children: [ + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + Navigator.of(context).pushNamed( + '/router/system_details', + arguments: {"msgType": 6}, + ).then((value) { + setState(() { + msgNumber["6"] = 0; + }); + }); + }, + child: messageItem("assets/image/icon_pl.webp", S.of(context).pinglun, msgNumber["6"].toString()), ), - ), + Container( + width: double.infinity, + height: 1.h, + margin: EdgeInsets.symmetric( + horizontal: 20, + ), + color: Color(0xFFF7F7F7), + ), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + Navigator.of(context).pushNamed('/router/system_details', + arguments: {"msgType": 5}).then((value) { + setState(() { + msgNumber["5"] = 0; + }); + }); + }, + child: messageItem("assets/image/icon_z.webp", + S.of(context).dianzan, msgNumber["5"].toString()), + ), + Container( + width: double.infinity, + height: 1.h, + margin: EdgeInsets.symmetric( + horizontal: 20, + ), + color: Color(0xFFF7F7F7), + ), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + Navigator.of(context).pushNamed('/router/system_details', + arguments: {"msgType": 4}).then((value) { + setState(() { + msgNumber["4"] = 0; + }); + }); + }, + child: messageItem("assets/image/icon_gz.webp", + S.of(context).guanzhu, msgNumber["4"].toString()), + ), + Container( + width: double.infinity, + height: 1.h, + margin: EdgeInsets.symmetric( + horizontal: 20, + ), + color: Color(0xFFF7F7F7), + ), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + Navigator.of(context) + .pushNamed('/router/system_notice') + .then((value) { + setState(() { + msgNumber["2"] = 0; + msgNumber["3"] = 0; + }); + }); + }, + child: messageItem( + "assets/image/icon_system_message_new.webp", + S.of(context).xitongxiaoxi, + "${(msgNumber["2"] ?? 0) + (msgNumber["3"] ?? 0)}"), + ), + // newsSurvey(), + // SizedBox( + // height: 16.h, + // ), + // buildMessage(), + ], ), ), ), @@ -305,85 +288,73 @@ class _SystemMessagePage extends State { Widget messageItem(img, title, messageNum) { return Container( - padding: EdgeInsets.only( - top: 14.h, - left: 14.w, - bottom: 10.h, - right: 14.w, + padding: EdgeInsets.symmetric( + horizontal: 14.w, + vertical: 14, ), decoration: BoxDecoration( color: Colors.white, ), - child: Column( + child: Row( children: [ - Row( - children: [ - Image.asset( - img, - fit: BoxFit.fill, + Image.asset( + img, + fit: BoxFit.fill, + ), + SizedBox( + width: 12.w, + ), + Text( + title, + style: TextStyle( + fontSize: 14.sp, + color: Color(0xFF060606), + fontWeight: MyFontWeight.semi_bold, + ), + ), + SizedBox( + width: 9.w, + ), + if (messageNum != "0") + (((double.tryParse(messageNum) ?? 0) < 100) + ? Container( + width: 16, + height: 16, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(100), + color: Color(0xFFFF441A), ), - SizedBox( - width: 12.w, + child: RoundButton( + text: messageNum, + textColor: Colors.white, + fontWeight: MyFontWeight.regular, + backgroup: Color(0xFFFF441A), + fontSize: 10.sp, + radius: 100, ), - Text( - title, - style: TextStyle( - fontSize: 14.sp, - color: Color(0xFF060606), - fontWeight: MyFontWeight.semi_bold, - ), + ) + : Container( + padding: EdgeInsets.symmetric( + horizontal: 4.w, vertical: 2.h, ), - SizedBox( - width: 9.w, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(100), + color: Color(0xFFFF441A), ), - if (messageNum != "0") - (((double.tryParse(messageNum) ?? 0) < 100) - ? Container( - width: 16, - height: 16, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(100), - color: Color(0xFFFF441A), - ), - child: RoundButton( - text: messageNum, - textColor: Colors.white, - fontWeight: MyFontWeight.regular, - backgroup: Color(0xFFFF441A), - fontSize: 10.sp, - radius: 100, - ), - ) - : Container( - padding: EdgeInsets.symmetric( - horizontal: 4.w, vertical: 2.h), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(100), - color: Color(0xFFFF441A), - ), - child: RoundButton( - text: "99+", - textColor: Colors.white, - fontWeight: MyFontWeight.regular, - backgroup: Color(0xFFFF441A), - fontSize: 10.sp, - radius: 100, - ), - )), - Spacer(), - Icon( - Icons.keyboard_arrow_right, - size: 24, + child: RoundButton( + text: "99+", + textColor: Colors.white, + fontWeight: MyFontWeight.regular, + backgroup: Color(0xFFFF441A), + fontSize: 10.sp, + radius: 100, ), - ], + )), + Spacer(), + Icon( + Icons.keyboard_arrow_right, + size: 24, ), - if (title != S.of(context).xitongxiaoxi) - Container( - margin: EdgeInsets.only(top: 12.h), - width: double.infinity, - height: 1.h, - color: Color(0xFFF7F7F7), - ), ], ), ); diff --git a/lib/message/system_notice.dart b/lib/message/system_notice.dart index c8a850e5..d8ae2191 100644 --- a/lib/message/system_notice.dart +++ b/lib/message/system_notice.dart @@ -6,6 +6,7 @@ import 'package:huixiang/data/message.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; @@ -39,12 +40,8 @@ class _SystemNotice extends State { void initState() { super.initState(); // msgType = widget.arguments["msgType"]; - - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), token: value.getString("token"), context: context); - queryMessage(); - }); + apiService = ApiService(Dio(), token: SharedInstance.instance.token, context: context); + queryMessage(); } _refresh() { @@ -62,6 +59,7 @@ class _SystemNotice extends State { }).catchError((onError) { _refreshController.loadFailed(); _refreshController.refreshFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -121,7 +119,8 @@ class _SystemNotice extends State { padding: EdgeInsets.only( top: MediaQuery.of(context).padding.top + 10.h, bottom: 10.h, - right: 16.w), + right: 16.w, + ), child: Row( children: [ GestureDetector( @@ -199,14 +198,18 @@ class _SystemNotice extends State { }, child: buildMessageItem(messages[position]), ); - }), + }, + ), ], - )); + ), + ); } Widget buildMessageItem(Message message) { return Container( - margin: EdgeInsets.only(top: 8.h, bottom: 8.h, left: 16.w, right: 17.w), + margin: EdgeInsets.only( + top: 8.h, bottom: 8.h, left: 16.w, right: 17.w, + ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, @@ -246,7 +249,8 @@ class _SystemNotice extends State { fontWeight: MyFontWeight.semi_bold, color: Color(0xFF060606), ), - )), + ), + ), Text( message.updateTime ?? "", style: TextStyle( diff --git a/lib/mine/coupon_page.dart b/lib/mine/coupon_page.dart index cb585b98..f9d36080 100644 --- a/lib/mine/coupon_page.dart +++ b/lib/mine/coupon_page.dart @@ -6,6 +6,7 @@ import 'package:huixiang/data/coupon.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/coupon_details_dialog.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -43,12 +44,8 @@ class _CouponPage extends State { @override void initState() { super.initState(); - - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), context: context, token: value.getString('token')); - queryCard(); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryCard(); _refreshController = RefreshController(initialRefresh: false); } @@ -74,6 +71,7 @@ class _CouponPage extends State { setState(() {}); _refreshController.loadFailed(); _refreshController.refreshFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (baseData?.data?.list?.isNotEmpty ?? false) { diff --git a/lib/mine/coupons_page.dart b/lib/mine/coupons_page.dart index 628d30f6..aedaf924 100644 --- a/lib/mine/coupons_page.dart +++ b/lib/mine/coupons_page.dart @@ -6,6 +6,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/coupon.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/coupon_details_dialog.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -38,10 +39,8 @@ class _CouponsPage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = ApiService(Dio(), context: context, token: value.getString('token')); - queryCard(); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryCard(); _refreshController = RefreshController(initialRefresh: false); } diff --git a/lib/mine/fans_page.dart b/lib/mine/fans_page.dart index 8487d6d6..ee601a73 100644 --- a/lib/mine/fans_page.dart +++ b/lib/mine/fans_page.dart @@ -6,6 +6,7 @@ import 'package:huixiang/data/follow.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -39,16 +40,13 @@ class _FansPage extends State with SingleTickerProviderStateMixin, Aut super.initState(); _refreshController = RefreshController(); - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), context: context, token: value.getString("token")); - _queryFollowList(); - }); + apiService = + ApiService(Dio(), context: context, token: SharedInstance.instance.token); + _queryFollowList(); } ///我的关注列表 _queryFollowList() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); BaseData>? baseData = await apiService?.followList({ "isMyFans": true, "pageNum": 1, @@ -56,7 +54,7 @@ class _FansPage extends State with SingleTickerProviderStateMixin, Aut }).catchError((error) { _refreshController.refreshFailed(); _refreshController.loadFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); _refreshController.refreshCompleted(); @@ -68,7 +66,6 @@ class _FansPage extends State with SingleTickerProviderStateMixin, Aut } list.addAll(baseData!.data!.list!); } - print("list: ${list.length}"); if ((int.tryParse("${baseData?.data?.total}") ?? 0) < (pageNum * 10)) { _refreshController.loadNoData(); } @@ -79,19 +76,18 @@ class _FansPage extends State with SingleTickerProviderStateMixin, Aut //关注/取关会员 _vipFollow(followId,isFollow) async { BaseData? baseData = await apiService?.follow(followId).catchError((onError) { - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { widget.refresh(); _queryFollowList(); SmartDialog.showToast(isFollow?"取关成功":"关注成功", alignment: Alignment.center); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @override Widget build(BuildContext context) { + super.build(context); return Scaffold( body: Container( margin: EdgeInsets.only(top: 2), @@ -128,7 +124,7 @@ class _FansPage extends State with SingleTickerProviderStateMixin, Aut child: fansItem(list[position]), ); }, - ) + ), // NoDataView( // isShowBtn: false, // text: "共关注0人", diff --git a/lib/mine/follow_page.dart b/lib/mine/follow_page.dart index 910810f6..44a9bec4 100644 --- a/lib/mine/follow_page.dart +++ b/lib/mine/follow_page.dart @@ -6,6 +6,7 @@ import 'package:huixiang/data/follow.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -36,17 +37,13 @@ class _FollowPage extends State void initState() { super.initState(); _refreshController = RefreshController(); - - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), context: context, token: value.getString("token")); - _queryFollowList(); - }); + apiService = + ApiService(Dio(), context: context, token: SharedInstance.instance.token); + _queryFollowList(); } ///我的关注列表 _queryFollowList() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); BaseData>? baseData = await apiService?.followList({ "isMyFans": false, "pageNum": 1, @@ -54,7 +51,7 @@ class _FollowPage extends State }).catchError((error) { _refreshController.refreshFailed(); _refreshController.loadFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); _refreshController.refreshCompleted(); @@ -88,6 +85,7 @@ class _FollowPage extends State @override Widget build(BuildContext context) { + super.build(context); return Scaffold( body: Container( margin: EdgeInsets.only(top: 2), diff --git a/lib/mine/invitation_record.dart b/lib/mine/invitation_record.dart index 351c607c..d930d158 100644 --- a/lib/mine/invitation_record.dart +++ b/lib/mine/invitation_record.dart @@ -12,6 +12,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -35,12 +36,9 @@ class _InvitationRecord extends State @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = ApiService(Dio(), - context: context, token: value.getString("token"), pay: true); - queryInviteMember(); - queryUserInfo(); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token, pay: true); + queryInviteMember(); + queryUserInfo(); } ///邀请记录 @@ -52,7 +50,7 @@ class _InvitationRecord extends State "pageSize": 100, }).catchError((error) { _refreshController.refreshFailed(); - return Future.value(null); + return BaseData>() ..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (baseData?.data?.list?.isNotEmpty ?? false) { @@ -70,20 +68,15 @@ class _InvitationRecord extends State } queryUserInfo() async { - BaseData? baseDate = - await apiService?.queryInfo().catchError((onError) { + BaseData? baseDate = await apiService?.queryInfo().catchError((onError) { _refreshController.refreshFailed(); - return Future.value(null); + return BaseData()..isSuccess = false; }); - if (baseDate?.isSuccess ?? false) { + if ((baseDate?.isSuccess ?? false) && baseDate!.data != null) { setState(() { - userInfo = baseDate!.data; + userInfo = baseDate.data; }); - SharedPreferences.getInstance().then( - (value) => { - value.setString('user', jsonEncode(baseDate!.data)), - }, - ); + SharedInstance.instance.saveUser(baseDate.data!); _refreshController.refreshCompleted(); } else { _refreshController.refreshFailed(); diff --git a/lib/mine/manage_address_page.dart b/lib/mine/manage_address_page.dart index 0e5ffc81..7a492ee3 100644 --- a/lib/mine/manage_address_page.dart +++ b/lib/mine/manage_address_page.dart @@ -6,6 +6,7 @@ import 'package:huixiang/data/address.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/icon_text.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -32,17 +33,14 @@ class _ManageAddressPage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, token: value.getString('token')), - queryMemberAddress(), - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryMemberAddress(); } List
? addressList; queryMemberAddress() async { - BaseListData
? baseData = await apiService?.queryMemberAddress().catchError((){ + BaseListData
? baseData = await apiService?.queryMemberAddress().catchError((error){ return BaseListData
()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { diff --git a/lib/mine/mine_card_invalid_page.dart b/lib/mine/mine_card_invalid_page.dart index 2fa780cb..85278d68 100644 --- a/lib/mine/mine_card_invalid_page.dart +++ b/lib/mine/mine_card_invalid_page.dart @@ -5,11 +5,11 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/coupon.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/coupon_widget.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class MineCardInvalidPage extends StatefulWidget { @@ -34,10 +34,8 @@ class _MineCardInvalidPage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), context: context, token: value.getString('token')), - queryCard(), - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryCard(); _refreshController = RefreshController(initialRefresh: false); } @@ -60,7 +58,7 @@ class _MineCardInvalidPage extends State { }).catchError((error) { _refreshController.loadFailed(); _refreshController.refreshFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (baseData?.data?.list?.isNotEmpty ?? false) { diff --git a/lib/mine/mine_greenery.dart b/lib/mine/mine_greenery.dart index 3eb32f4f..9cceb8b2 100644 --- a/lib/mine/mine_greenery.dart +++ b/lib/mine/mine_greenery.dart @@ -9,6 +9,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -35,12 +36,9 @@ class _MineGreenery extends State { @override void initState() { super.initState(); - - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, token: value.getString("token")), - pointGoodsList(), - }); + apiService = ApiService(Dio(), + context: context, token: SharedInstance.instance.token); + pointGoodsList(); } pointGoodsList() async { @@ -56,7 +54,7 @@ class _MineGreenery extends State { await apiService?.creditGoods(param).catchError((onError) { refreshController.loadFailed(); refreshController.refreshFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); SmartDialog.dismiss(); if (pageGoods?.isSuccess ?? false) { @@ -228,7 +226,7 @@ class _MineGreenery extends State { children: [ Expanded( child: GridView.builder( - itemCount: goods.length ?? 0, + itemCount: goods.length, padding: EdgeInsets.only( left: 16.w, right: 16.w, diff --git a/lib/mine/mine_page.dart b/lib/mine/mine_page.dart index f2f83a01..4974602f 100644 --- a/lib/mine/mine_page.dart +++ b/lib/mine/mine_page.dart @@ -21,11 +21,11 @@ import 'package:huixiang/mine/mine_view/mine_navbar.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:retrofit/error_logger.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import '../data/banner.dart'; import '../data/coupon.dart'; @@ -54,18 +54,23 @@ class MinePageState extends State with AutomaticKeepAliveClientMixin, List activityBannerData = []; _toUserInfo() async { - SharedPreferences shared = await SharedPreferences.getInstance(); - if (shared.getString("token") == null || shared.getString("token") == "") { + if (SharedInstance.instance.token.isEmpty) { Navigator.of(context).pushReplacementNamed('/router/new_login_page', arguments: {"login": "login"}); return; } - (Platform.isAndroid && ExamineInstance.instance.isExamine) - ? await Navigator.of(context).pushNamed('/router/user_info_page') - : await Navigator.of(context) - .pushNamed('/router/personal_page', arguments: { - "memberId": "0", - }); + if (Platform.isAndroid && ExamineInstance.instance.isExamine) { + await Navigator.of(context).pushNamed('/router/user_info_page'); + } else { + if (SharedInstance.instance.userId.isNotEmpty) { + await Navigator.of(context).pushNamed( + '/router/personal_page', + arguments: { + "memberId": SharedInstance.instance.userId, + }, + ); + } + } setState(() {}); } @@ -96,18 +101,11 @@ class MinePageState extends State with AutomaticKeepAliveClientMixin, } queryUserInfo() async { - // SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai); - - final SharedPreferences value = await SharedPreferences.getInstance(); - if (value.containsKey('user') && - value.getString('user') != null && - value.getString('user') != "") { - userInfo = UserInfo.fromJson(jsonDecode(value.getString('user')!)); - } + userInfo = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)); apiService = ApiService( Dio(), context: context, - token: value.getString('token'), + token: SharedInstance.instance.token, showLoading: false, errorLogger: this, ); @@ -128,13 +126,9 @@ class MinePageState extends State with AutomaticKeepAliveClientMixin, _refreshController.refreshFailed(); return BaseData()..isSuccess = false; }); - if (baseDate?.isSuccess ?? false) { + if ((baseDate?.isSuccess ?? false) && baseDate?.data != null) { userInfo = baseDate?.data; - SharedPreferences.getInstance().then( - (value) => { - value.setString('user', jsonEncode(baseDate?.data)), - }, - ); + SharedInstance.instance.saveUser(baseDate!.data!); _refreshController.refreshCompleted(); } else { _refreshController.refreshFailed(); @@ -144,11 +138,10 @@ class MinePageState extends State with AutomaticKeepAliveClientMixin, ///宣传banner queryActivityBanner() async { - SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService( Dio(), context: context, - token: value.getString("token"), + token: SharedInstance.instance.token, showLoading: false, errorLogger: this, ); @@ -163,11 +156,10 @@ class MinePageState extends State with AutomaticKeepAliveClientMixin, } queryCoupon() async { - SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService( Dio(), context: context, - token: value.getString("token"), + token: SharedInstance.instance.token, showLoading: false, errorLogger: this, ); @@ -199,11 +191,10 @@ class MinePageState extends State with AutomaticKeepAliveClientMixin, ///个人社交信息(粉丝/关注数量/成就数量) querySocialInfo() async { - SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService( Dio(), context: context, - token: value.getString("token"), + token: SharedInstance.instance.token, showLoading: false, errorLogger: this, ); @@ -222,8 +213,7 @@ class MinePageState extends State with AutomaticKeepAliveClientMixin, ///消息数量 queryMsgStats() async { - BaseListData? baseData = - await apiService?.stats().catchError((onError) { + BaseListData? baseData = await apiService?.stats().catchError((onError) { return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -764,8 +754,7 @@ class MinePageState extends State with AutomaticKeepAliveClientMixin, } toIntegralPage() async { - SharedPreferences shared = await SharedPreferences.getInstance(); - if (shared.getString("token") == null || shared.getString("token") == "") { + if (SharedInstance.instance.token.isEmpty) { LoginTipsDialog().show(context); return; } diff --git a/lib/mine/mine_shop_details.dart b/lib/mine/mine_shop_details.dart index 40380927..f2f1a8e5 100644 --- a/lib/mine/mine_shop_details.dart +++ b/lib/mine/mine_shop_details.dart @@ -15,6 +15,7 @@ import 'package:huixiang/store/scan.dart'; import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/utils/location.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -38,7 +39,6 @@ class _MineShopDetails extends State { ApiService? apiService; int selectType = 0; List userBill = []; - int networkStatus = 0; @override void dispose() { @@ -51,11 +51,11 @@ class _MineShopDetails extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), token: value.getString("token"), context: context); - vipDetail("", ""); - }); + apiService = ApiService(Dio(), + token: SharedInstance.instance.token, + context: context, + ); + vipDetail("", ""); startLocation(); } @@ -65,28 +65,30 @@ class _MineShopDetails extends State { int current = 1; vipDetail(latitude, longitude) async { - SharedPreferences value = await SharedPreferences.getInstance(); BaseData? baseData = await apiService?.vipDetail({ "id": widget.arguments["id"], "latitude": "$latitude", "longitude": "$longitude", }).catchError((onError) { - networkStatus = -1; - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { vipCard = baseData!.data; + if ((vipCard?.storeList?.isNotEmpty ?? false) && + (vipCard!.storeList!.first.logo?.isNotEmpty ?? false)) { + Color? color = await loadShopColor(vipCard!.storeList!.first.logo!); + if (color != null) { + vipCard!.color = color; + } + } refreshController.loadComplete(); - networkStatus = 1; } else { refreshController.loadFailed(); } - print("object:object"); setState(() {}); } startLocation() async { - // SmartDialog.showLoading(msg: S.current.zhengzaijiazai); LocationInstance.getInstance().startLocation(context, (Position? result) { if (result?.latitude != null && result?.longitude != null) { vipDetail(result?.latitude, result?.longitude); @@ -109,12 +111,11 @@ class _MineShopDetails extends State { "size": 10, "sort": "id" }).catchError((onError) { - networkStatus == -1; refreshController.refreshFailed(); refreshController.loadFailed(); consumeRefreshController.refreshFailed(); consumeRefreshController.loadFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (current == 1) { @@ -133,7 +134,6 @@ class _MineShopDetails extends State { } else { current += 1; } - networkStatus = 1; } else { refreshController.refreshFailed(); refreshController.loadFailed(); @@ -153,138 +153,136 @@ class _MineShopDetails extends State { systemUiOverlayStyle: SystemUiOverlayStyle.dark, leadingColor: Colors.black, ), - body: networkStatus == 0 - ? skeletonScreen() - : Column( + body: Column( + children: [ + buildVipCard(), + Container( + margin: EdgeInsets.only(left: 14.w), + child: Row( children: [ - buildVipCard(), - Container( - margin: EdgeInsets.only(left: 14.w), - child: Row( + GestureDetector( + onTap: () { + setState(() { + selectType = 0; + }); + }, + child: Column( children: [ - GestureDetector( - onTap: () { - setState(() { - selectType = 0; - }); - }, - child: Column( - children: [ - Text( - "适用门店", - style: TextStyle( - color: Color( - selectType == 0 ? 0xFF000000 : 0xFF868686), - fontSize: 15.sp, - fontWeight: MyFontWeight.medium, - ), - ), - SizedBox( - height: 8.h, - ), - if (selectType == 0) - Container( - width: 52.w, - height: 2.h, - color: Color(0xFF32A060), - ) - ], + Text( + "适用门店", + style: TextStyle( + color: + Color(selectType == 0 ? 0xFF000000 : 0xFF868686), + fontSize: 15.sp, + fontWeight: MyFontWeight.medium, ), ), SizedBox( - width: 20.w, + height: 8.h, ), - // GestureDetector( - // onTap: () { - // setState(() { - // selectType = 1; - // billInfo(); - // }); - // }, - // child: Column( - // children: [ - // Text( - // "余额明细", - // style: TextStyle( - // color: - // Color(selectType == 1 ? 0xFF000000 : 0xFF868686), - // fontSize: 15.sp, - // fontWeight: MyFontWeight.medium, - // ), - // ), - // SizedBox( - // height: 8.h, - // ), - // if (selectType == 1) - // Container( - // width: 52.w, - // height: 2.h, - // color: Color(0xFF32A060), - // ) - // ], - // ), - // ), + if (selectType == 0) + Container( + width: 52.w, + height: 2.h, + color: Color(0xFF32A060), + ) ], ), ), - selectType == 0 - ? Expanded( - child: SmartRefresher( - controller: refreshController, - enablePullDown: false, - enablePullUp: false, - footer: CustomFooter( - builder: (context, mode) { - return MyFooter(mode); - }, - ), - physics: BouncingScrollPhysics(), - child: ListView.builder( - itemBuilder: (context, position) { - return GestureDetector( - onTap: () {}, - child: shopItem(vipCard!.storeList![position]), - ); - }, - padding: EdgeInsets.symmetric(vertical: 1), - itemCount: vipCard?.storeList?.length ?? 0, - ), - ), - ) - : Expanded( - child: SmartRefresher( - controller: consumeRefreshController, - enablePullDown: true, - enablePullUp: true, - physics: BouncingScrollPhysics(), - header: MyHeader(), - footer: CustomFooter( - builder: (context, mode) { - return MyFooter(mode); - }, - ), - onRefresh: () { - current = 1; - billInfo(); - }, - onLoading: () { - billInfo(); - }, - child: ListView.builder( - itemBuilder: (context, position) { - return GestureDetector( - onTap: () {}, - child: consumeItem(userBill[position]), - ); - }, - shrinkWrap: true, - padding: EdgeInsets.symmetric(vertical: 1), - itemCount: userBill.length ?? 0, - ), - ), - ), + SizedBox( + width: 20.w, + ), + // GestureDetector( + // onTap: () { + // setState(() { + // selectType = 1; + // billInfo(); + // }); + // }, + // child: Column( + // children: [ + // Text( + // "余额明细", + // style: TextStyle( + // color: + // Color(selectType == 1 ? 0xFF000000 : 0xFF868686), + // fontSize: 15.sp, + // fontWeight: MyFontWeight.medium, + // ), + // ), + // SizedBox( + // height: 8.h, + // ), + // if (selectType == 1) + // Container( + // width: 52.w, + // height: 2.h, + // color: Color(0xFF32A060), + // ) + // ], + // ), + // ), ], ), + ), + selectType == 0 + ? Expanded( + child: SmartRefresher( + controller: refreshController, + enablePullDown: false, + enablePullUp: false, + footer: CustomFooter( + builder: (context, mode) { + return MyFooter(mode); + }, + ), + physics: BouncingScrollPhysics(), + child: ListView.builder( + itemBuilder: (context, position) { + return GestureDetector( + onTap: () {}, + child: shopItem(vipCard!.storeList![position]), + ); + }, + padding: EdgeInsets.symmetric(vertical: 1), + itemCount: vipCard?.storeList?.length ?? 0, + ), + ), + ) + : Expanded( + child: SmartRefresher( + controller: consumeRefreshController, + enablePullDown: true, + enablePullUp: true, + physics: BouncingScrollPhysics(), + header: MyHeader(), + footer: CustomFooter( + builder: (context, mode) { + return MyFooter(mode); + }, + ), + onRefresh: () { + current = 1; + billInfo(); + }, + onLoading: () { + billInfo(); + }, + child: ListView.builder( + itemBuilder: (context, position) { + return GestureDetector( + onTap: () {}, + child: consumeItem(userBill[position]), + ); + }, + shrinkWrap: true, + padding: EdgeInsets.symmetric(vertical: 1), + itemCount: userBill.length ?? 0, + ), + ), + ), + ], + ), ); } @@ -319,7 +317,15 @@ class _MineShopDetails extends State { topLeft: Radius.circular(6), topRight: Radius.circular(6), ), - color: Color(colorByName(vipCard?.tenantName ?? "")), + color: vipCard?.color ?? Color(colorByName(vipCard?.tenantName ?? "")), + boxShadow: [ + BoxShadow( + color: (vipCard?.color ?? Color(colorByName(vipCard?.tenantName ?? ""))).withAlpha(80), + offset: Offset(0, -1), + blurRadius: 3, + spreadRadius: 1, + ), + ], ), padding: EdgeInsets.only(left: 12.w), height: 62.h, @@ -355,6 +361,14 @@ class _MineShopDetails extends State { topRight: Radius.circular(6), ), color: Colors.white, + boxShadow: [ + BoxShadow( + color: (vipCard?.color ?? Color(colorByName(vipCard?.tenantName ?? ""))).withAlpha(10), + offset: Offset(0, 2), + blurRadius: 5, + spreadRadius: 1, + ), + ], ), padding: EdgeInsets.all(12.h), child: Column( @@ -823,58 +837,58 @@ class _MineShopDetails extends State { bool isRemake = true; - // String totalPrice(orderInfo) { - // if (orderInfo == null) return ""; - // double totalPrice = (double.tryParse(orderInfo.orderSum) + - // double.tryParse(orderInfo.postFee)); - // if (orderInfo.orderDetail != null && - // orderInfo.orderDetail.couponDTO != null) { - // totalPrice -= double.tryParse(orderInfo.orderDetail.couponDTO.money); - // } - // return "$totalPrice"; - // } - // List goodsItem(List products) { - // if (products.length > 3) { - // products = products.sublist(0, 3); - // } - // return products - // .map( - // (e) => Container( - // margin: EdgeInsets.symmetric(horizontal: 2.w), - // child: Column( - // mainAxisAlignment: MainAxisAlignment.spaceAround, - // crossAxisAlignment: CrossAxisAlignment.center, - // children: [ - // MImage( - // e.skuImg, - // width: 75.w, - // height: 75.h, - // fit: BoxFit.contain, - // errorSrc: "assets/image/default_1.webp", - // fadeSrc: "assets/image/default_1.webp", - // ), - // SizedBox( - // height: 4.h, - // ), - // if (isRemake) - // Container( - // width: 75.w, - // child: Text( - // e.productName, - // maxLines: 1, - // textAlign: TextAlign.center, - // overflow: TextOverflow.ellipsis, - // style: TextStyle( - // fontSize: 10.sp, - // fontWeight: MyFontWeight.regular, - // color: Color(0xFF353535), - // ), - // ), - // ), - // ], - // ), - // ), - // ) - // .toList(); - // } +// String totalPrice(orderInfo) { +// if (orderInfo == null) return ""; +// double totalPrice = (double.tryParse(orderInfo.orderSum) + +// double.tryParse(orderInfo.postFee)); +// if (orderInfo.orderDetail != null && +// orderInfo.orderDetail.couponDTO != null) { +// totalPrice -= double.tryParse(orderInfo.orderDetail.couponDTO.money); +// } +// return "$totalPrice"; +// } +// List goodsItem(List products) { +// if (products.length > 3) { +// products = products.sublist(0, 3); +// } +// return products +// .map( +// (e) => Container( +// margin: EdgeInsets.symmetric(horizontal: 2.w), +// child: Column( +// mainAxisAlignment: MainAxisAlignment.spaceAround, +// crossAxisAlignment: CrossAxisAlignment.center, +// children: [ +// MImage( +// e.skuImg, +// width: 75.w, +// height: 75.h, +// fit: BoxFit.contain, +// errorSrc: "assets/image/default_1.webp", +// fadeSrc: "assets/image/default_1.webp", +// ), +// SizedBox( +// height: 4.h, +// ), +// if (isRemake) +// Container( +// width: 75.w, +// child: Text( +// e.productName, +// maxLines: 1, +// textAlign: TextAlign.center, +// overflow: TextOverflow.ellipsis, +// style: TextStyle( +// fontSize: 10.sp, +// fontWeight: MyFontWeight.regular, +// color: Color(0xFF353535), +// ), +// ), +// ), +// ], +// ), +// ), +// ) +// .toList(); +// } } diff --git a/lib/mine/mine_shop_page.dart b/lib/mine/mine_shop_page.dart index e63639c2..5225f40f 100644 --- a/lib/mine/mine_shop_page.dart +++ b/lib/mine/mine_shop_page.dart @@ -1,4 +1,10 @@ +import 'dart:async'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:color_thief_dart/color_thief_dart.dart'; import 'package:dio/dio.dart'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; @@ -6,14 +12,15 @@ import 'package:huixiang/data/base_list_data.dart'; import 'package:huixiang/data/vip_card.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:shimmer/shimmer.dart'; class MineShopPage extends StatefulWidget { @@ -42,11 +49,8 @@ class _MineShopPage extends State with WidgetsBindingObserver { void initState() { super.initState(); refreshController = RefreshController(); - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), context: context, token: value.getString("token")); - queryVipCard(); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryVipCard(); _focusNode.addListener(() { setState(() { hasFocus = _focusNode.hasFocus; @@ -97,6 +101,7 @@ class _MineShopPage extends State with WidgetsBindingObserver { if (baseData?.isSuccess ?? false) { coupons.clear(); coupons.addAll(baseData!.data ?? []); + await loadShopColors(); refreshController.refreshCompleted(); networkStatus = 1; } else { @@ -108,6 +113,19 @@ class _MineShopPage extends State with WidgetsBindingObserver { } } + Future loadShopColors() async { + await Future.forEach(coupons, (element) async { + if ((element.storeList?[0].logo ?? "").isEmpty) { + return; + } + Color? color = await loadShopColor(element.storeList![0].logo!); + if (color != null) { + element.color = color; + } + }); + setState(() {}); + } + @override Widget build(BuildContext context) { return GestureDetector( @@ -129,7 +147,7 @@ class _MineShopPage extends State with WidgetsBindingObserver { color: Colors.white, padding: EdgeInsets.only( top: 10.h, - bottom: 18.h, + bottom: 18, ), child: searchShop(), ), @@ -157,7 +175,7 @@ class _MineShopPage extends State with WidgetsBindingObserver { ) : ((coupons.length > 0) ? ListView.builder( - padding: EdgeInsets.symmetric(vertical: 8.h), + padding: EdgeInsets.symmetric(vertical: 8), itemBuilder: (context, position) { return GestureDetector( onTap: () { @@ -165,11 +183,10 @@ class _MineShopPage extends State with WidgetsBindingObserver { '/router/mine_shop_recharge', arguments: { "id": coupons[position].id, - "tenantCode": - coupons[position].tenantCode, - "storeId": - coupons[position].storeList?[0].id - }).then((value) { + "tenantCode": coupons[position].tenantCode, + "storeId": coupons[position].storeList?[0].id + }, + ).then((value) { queryVipCard(showLoading: false); }); }, @@ -258,7 +275,6 @@ class _MineShopPage extends State with WidgetsBindingObserver { Widget shopItem(VipCard vipCard) { return Container( width: double.infinity, - margin: EdgeInsets.only(bottom: 12.h, top: 14.h, left: 14.w, right: 14.w), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, @@ -269,9 +285,18 @@ class _MineShopPage extends State with WidgetsBindingObserver { topLeft: Radius.circular(6), topRight: Radius.circular(6), ), - color: Color(colorByName(vipCard.tenantName)), + color: vipCard.color, + boxShadow: [ + BoxShadow( + color: vipCard.color.withAlpha(80), + offset: Offset(0, -1), + blurRadius: 3, + spreadRadius: 1, + ), + ], ), padding: EdgeInsets.only(left: 12.w), + margin: EdgeInsets.only(top: 12, left: 14.w, right: 14.w), height: 62.h, child: Row( children: [ @@ -302,11 +327,22 @@ class _MineShopPage extends State with WidgetsBindingObserver { decoration: BoxDecoration( borderRadius: new BorderRadius.only( bottomRight: Radius.circular(6), - topRight: Radius.circular(6), + bottomLeft: Radius.circular(6), ), color: Colors.white, + boxShadow: [ + BoxShadow( + color: vipCard.color.withAlpha(10), + offset: Offset(0, 2), + blurRadius: 5, + spreadRadius: 1, + ), + ], ), padding: EdgeInsets.all(12.h), + margin: EdgeInsets.only( + bottom: 12, left: 14.w, right: 14.w, + ), child: Column( children: [ Row( diff --git a/lib/mine/mine_shop_recharge.dart b/lib/mine/mine_shop_recharge.dart index bb7f3bd5..e562040f 100644 --- a/lib/mine/mine_shop_recharge.dart +++ b/lib/mine/mine_shop_recharge.dart @@ -15,10 +15,10 @@ import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/store/scan.dart'; import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:shimmer/shimmer.dart'; import 'package:tobias/tobias.dart'; @@ -54,7 +54,6 @@ class _MineShopRecharge extends State { late String storeId; String? minToken; final RefreshController refreshController = RefreshController(); - int networkStatus = 0; @override void dispose() { @@ -70,6 +69,11 @@ class _MineShopRecharge extends State { super.initState(); storeId = widget.arguments["storeId"]; tenant = widget.arguments["tenantCode"]; + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); _onRefresh(); fluwx.addSubscriber((event) async { @@ -91,11 +95,17 @@ class _MineShopRecharge extends State { "latitude": "", "longitude": "", }).catchError((onError) { - networkStatus = -1; + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { vipCard = baseData!.data; - networkStatus = 1; + if ((vipCard?.storeList?.isNotEmpty ?? false) && + (vipCard!.storeList!.first.logo?.isNotEmpty ?? false)) { + Color? color = await loadShopColor(vipCard!.storeList!.first.logo!); + if (color != null) { + vipCard!.color = color; + } + } } } finally { if (isSingle) @@ -107,41 +117,34 @@ class _MineShopRecharge extends State { ///小程序登录 minLogin() async { - try { - var baseData = await apiService?.minLogin(storeId).catchError((onError) { - debugPrint(onError.toString()); - }); - if (baseData?.isSuccess ?? false) { - minToken = baseData!.data["token"]; - SharedPreferences.getInstance().then( - (value) => { - value.setString('minToken', "${minToken}"), - value.setString('tenant', tenant), - value.setString('storeId', storeId), - }, - ); - minService = MinApiService( - Dio(), - context: context, - token: minToken, - tenant: tenant, - storeId: storeId, - ); - } - } finally {} + var baseData = await apiService?.minLogin(storeId).catchError((onError) { + debugPrint(onError.toString()); + return BaseData()..isSuccess = false; + }); + if (baseData?.isSuccess ?? false) { + minToken = baseData!.data["token"]; + SharedInstance.instance.saveMini("${minToken}", tenant, storeId); + minService = MinApiService( + Dio(), + context: context, + token: minToken, + tenant: tenant, + storeId: storeId, + ); + } } ///充值列表 queryRechargeActList() async { + if (minService == null) { + await minLogin(); + } try { - BaseListData? baseData = - await minService?.memberRechargeList().catchError((onError) { - networkStatus = -1; + BaseListData? baseData = await minService?.memberRechargeList().catchError((onError) { return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { memberRechargeList = baseData!.data ?? []; - networkStatus = 1; } } finally { addLoadCount(); @@ -154,19 +157,13 @@ class _MineShopRecharge extends State { "money": 0, "rechargeId": memberRechargeList[selectIndex].id, "type": checkIndex == 2 ? "wechat" : "alipay", - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { if (checkIndex == 2) { - // if (Platform.isAndroid) { - // if (!(await Min.isInitialize())) { - // // 小程序的微信支付和app的充值支付使用同一个WXPayEntryActivity回调, - // // 然而充值时小程序未初始化会导致回调内部代码调用getPackage空指针, - // // 故而在此初始化一下 - // await Min.initialize(); - // } - // } WxPay? wxPay = WxPay.fromJson(baseData!.data); - if (wxPay?.isAnyEmpty() ?? true) { + if (wxPay.isAnyEmpty()) { return; } await fluwx.registerApi( @@ -174,8 +171,7 @@ class _MineShopRecharge extends State { doOnAndroid: true, universalLink: "https://hx.lotus-wallet.com/app/", ); - fluwx.pay( - which: Payment( + fluwx.pay(which: Payment( appId: wxPay.appId!, partnerId: wxPay.partnerId!, prepayId: wxPay.prepayId!, @@ -250,516 +246,172 @@ class _MineShopRecharge extends State { controller: refreshController, onRefresh: _onRefresh, physics: BouncingScrollPhysics(), - child: networkStatus == 0 - ? skeletonScreen() - : Column( - children: [ - shopRechargeCard(), - (memberRechargeList?.isNotEmpty ?? false) - ? Expanded( - child: ListView.builder( - padding: EdgeInsets.zero, - itemCount: memberRechargeList.length ?? 0, - scrollDirection: Axis.vertical, - shrinkWrap: true, - physics: BouncingScrollPhysics(), - itemBuilder: (context, position) { - return GestureDetector( - onTap: () { - setState(() { - selectIndex = position; - }); - }, - child: rechargeItem( - memberRechargeList[position], position), - ); - }, - ), - ) - : NoDataView( - src: "assets/image/xiao_fei.webp", - isShowBtn: false, - text: "当前店铺暂无充值套餐~", - fontSize: 16.sp, - margin: EdgeInsets.only( - top: 90.h, - left: 60.w, - right: 60.w, - ), - ), - if (memberRechargeList?.isNotEmpty ?? false) - Container( - width: double.infinity, - margin: EdgeInsets.only(left: 16, right: 16), - padding: EdgeInsets.only( - top: 20.h, - bottom: 24.h, - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: EdgeInsets.only(bottom: 16.h), - child: Text( - S.of(context).zhifufangshi, - style: TextStyle( - fontSize: 16.sp, - color: Colors.black, - fontWeight: FontWeight.bold, - ), - ), - ), - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - setState(() { - checkIndex = 2; - }); - }, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Image.asset("assets/image/icon_we_chat.webp"), - Expanded( - flex: 1, - child: Padding( - padding: EdgeInsets.only(left: 8.w), - child: Text( - S.of(context).weixinzhifu, - style: TextStyle( - fontSize: 14.sp, - color: Color(0xff353535), - ), - ), - ), - ), - checkView(2), - ], - ), - ), - SizedBox(height: 10.h), - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - setState(() { - checkIndex = 3; - }); - }, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Image.asset("assets/image/icon_alipay.webp"), - Expanded( - flex: 1, - child: Padding( - padding: EdgeInsets.only(left: 8.w), - child: Text( - S.of(context).zhifubao, - style: TextStyle( - fontSize: 14.sp, - color: Color(0xff353535), - ), - ), - ), - ), - checkView(3), - ], - ), - ), - ], - ), - ), - if (memberRechargeList?.isNotEmpty ?? false) - Align( - alignment: Alignment.bottomCenter, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - shopRecharge(); - }, - child: Container( - height: 56.h, - width: double.infinity, - alignment: Alignment.center, - decoration: BoxDecoration( - color: Color(0xFF32A060), - borderRadius: BorderRadius.circular(27), - ), - margin: EdgeInsets.only( - top: 12.h, left: 16.w, right: 16.w, bottom: 21.h), - child: Text( - S.of(context).querenchongzhi, - style: TextStyle( - fontSize: 16.sp, - fontWeight: MyFontWeight.medium, - color: Colors.white, - ), - ), - ), - ), - ) - ], - ), - ), - ); - } - - ///卡片背景底色 - int colorByName(String storeName) { - if (storeName.contains("百年川椒") || storeName.contains("百年川椒")) { - return 0xFFC30D23; - } else if (storeName.contains("海峡姐妹") || storeName.contains("海峽姐妹")) { - return 0xFFE4C796; - } else if (storeName.contains("前进麦味") || storeName.contains("前進麥味")) { - return 0xFF265782; - } - return 0xFF32A060; - } - - ///整体骨架屏 - Widget skeletonScreen() { - return Container( child: Column( - children: [ - Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, children: [ - Container( - decoration: BoxDecoration( - borderRadius: new BorderRadius.only( - topLeft: Radius.circular(6), - topRight: Radius.circular(6), - ), - color: Color(0XFFD8D8D8), + shopRechargeCard(), + (memberRechargeList.isNotEmpty) + ? Expanded( + child: ListView.builder( + padding: EdgeInsets.zero, + itemCount: memberRechargeList.length, + scrollDirection: Axis.vertical, + shrinkWrap: true, + physics: BouncingScrollPhysics(), + itemBuilder: (context, position) { + return GestureDetector( + onTap: () { + setState(() { + selectIndex = position; + }); + }, + child: rechargeItem( + memberRechargeList[position], position), + ); + }, ), - height: 62.h, - ), - Container( - decoration: BoxDecoration( - borderRadius: new BorderRadius.only( - bottomRight: Radius.circular(6), - topRight: Radius.circular(6), - ), - color: Colors.white, - ), - padding: EdgeInsets.all(12.h), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 68.w, - height: 17.h, - ), - ), - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 120.w, - height: 17.h, - ), - ), - ], - ), - SizedBox( - height: 4.h, - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 99.w, - height: 34.h, - ), - ), - Spacer(), - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 48.w, - height: 17.h, - ), - ), - SizedBox( - width: 2, - ), - Image.asset( - "assets/image/icon_right_z.webp", - width: 16, - height: 16, - color: Color(0xFF262626), - ) - ], - ), - ], + ) + : NoDataView( + src: "assets/image/xiao_fei.webp", + isShowBtn: false, + text: "当前店铺暂无充值套餐~", + fontSize: 16.sp, + margin: EdgeInsets.only( + top: 90.h, + left: 60.w, + right: 60.w, ), ), - ], - ), - Expanded( - child: ListView.builder( - itemCount: 4, - physics: BouncingScrollPhysics(), - shrinkWrap: true, - itemBuilder: (context, position) { - return Container( + if (memberRechargeList.isNotEmpty) + Container( width: double.infinity, - height: 69.h, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(4), - color: Colors.white, + margin: EdgeInsets.only(left: 16, right: 16), + padding: EdgeInsets.only( + top: 20.h, + bottom: 24.h, ), - margin: EdgeInsets.only( - bottom: 14.h, - left: 14.w, - right: 14.w, - ), - padding: EdgeInsets.only(left: 16), - child: Flex( - direction: Axis.horizontal, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 20.w, - height: 15.h, - ), - ), - SizedBox( - width: 10.w, - ), - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 50.w, - height: 25.h, - ), + Padding( + padding: EdgeInsets.only(bottom: 16.h), + child: Text( + S.of(context).zhifufangshi, + style: TextStyle( + fontSize: 16.sp, + color: Colors.black, + fontWeight: FontWeight.bold, ), - ], - ), - Container( - width: 1.w, - height: 37.h, - color: Color(0xFF979797), - margin: EdgeInsets.only( - right: 16.w, - left: 12, ), ), - Expanded( - flex: 2, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + setState(() { + checkIndex = 2; + }); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 50.w, - height: 17.h, + Image.asset("assets/image/icon_we_chat.webp"), + Expanded( + flex: 1, + child: Padding( + padding: EdgeInsets.only(left: 8.w), + child: Text( + S.of(context).weixinzhifu, + style: TextStyle( + fontSize: 14.sp, + color: Color(0xff353535), ), ), - SizedBox( - width: 10.w, - ), - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 48.w, - height: 25.h, - ), - ), - ], - ), - SizedBox( - height: 4.h, + ), ), - Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 50.w, - height: 17.h, + checkView(2), + ], + ), + ), + SizedBox(height: 10.h), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + setState(() { + checkIndex = 3; + }); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Image.asset("assets/image/icon_alipay.webp"), + Expanded( + flex: 1, + child: Padding( + padding: EdgeInsets.only(left: 8.w), + child: Text( + S.of(context).zhifubao, + style: TextStyle( + fontSize: 14.sp, + color: Color(0xff353535), ), ), - Icon( - Icons.chevron_right, - size: 20, - color: Color(0xFF868686), - ), - ], - ) + ), + ), + checkView(3), ], ), - ) + ), ], ), - ); - }, - ), - ), - Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: EdgeInsets.only(bottom: 16.h), - child: Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 64.w, - height: 21.h, - ), ), - ), - Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 20.h, - height: 20.h, - ), - ), - Padding( - padding: EdgeInsets.only(left: 8.w), - child: Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 51.w, - height: 17.h, - ), - ), - ), - Spacer(), - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), + if (memberRechargeList.isNotEmpty) + Align( + alignment: Alignment.bottomCenter, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + shopRecharge(); + }, child: Container( + height: 56.h, + width: double.infinity, + alignment: Alignment.center, decoration: BoxDecoration( - color: Color(0XFFD8D8D8), - borderRadius: BorderRadius.circular(100), + color: Color(0xFF32A060), + borderRadius: BorderRadius.circular(27), ), - width: 15.h, - height: 15.h, - ), - ), - ], - ), - SizedBox(height: 10.h), - Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 20.h, - height: 20.h, - ), - ), - Padding( - padding: EdgeInsets.only(left: 8.w), - child: Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - color: Color(0XFFD8D8D8), - width: 51.w, - height: 17.h, + margin: EdgeInsets.only( + top: 12.h, left: 16.w, right: 16.w, bottom: 21.h, ), - ), - ), - Spacer(), - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - decoration: BoxDecoration( - color: Color(0XFFD8D8D8), - borderRadius: BorderRadius.circular(100), + child: Text( + S.of(context).querenchongzhi, + style: TextStyle( + fontSize: 16.sp, + fontWeight: MyFontWeight.medium, + color: Colors.white, + ), ), - width: 15.h, - height: 15.h, ), ), - ], - ), + ) ], ), - Shimmer.fromColors( - baseColor: Color(0XFFD8D8D8), - highlightColor: Color(0XFFD8D8D8), - child: Container( - height: 56.h, - width: double.infinity, - alignment: Alignment.center, - decoration: BoxDecoration( - color: Color(0XFFD8D8D8), - borderRadius: BorderRadius.circular(27), - ), - margin: EdgeInsets.only( - top: 12.h, - left: 16.w, - right: 16.w, - bottom: 21.h, - ), - ), - ) - ], - )); + ), + ); + } + + ///卡片背景底色 + int colorByName(String storeName) { + if (storeName.contains("百年川椒") || storeName.contains("百年川椒")) { + return 0xFFC30D23; + } else if (storeName.contains("海峡姐妹") || storeName.contains("海峽姐妹")) { + return 0xFFE4C796; + } else if (storeName.contains("前进麦味") || storeName.contains("前進麥味")) { + return 0xFF265782; + } + return 0xFF32A060; } ///卡片详情 @@ -767,8 +419,10 @@ class _MineShopRecharge extends State { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - Navigator.of(context).pushNamed('/router/mine_shop_details', - arguments: {"id": widget.arguments["id"]}); + Navigator.of(context).pushNamed( + '/router/mine_shop_details', + arguments: {"id": widget.arguments["id"]}, + ); }, child: Container( width: double.infinity, @@ -789,7 +443,15 @@ class _MineShopRecharge extends State { topLeft: Radius.circular(6), topRight: Radius.circular(6), ), - color: Color(colorByName(vipCard?.tenantName ?? "")), + color: vipCard?.color ?? Color(colorByName(vipCard?.tenantName ?? "")), + boxShadow: [ + BoxShadow( + color: (vipCard?.color ?? Color(colorByName(vipCard?.tenantName ?? ""))).withAlpha(80), + offset: Offset(0, -1), + blurRadius: 3, + spreadRadius: 1, + ), + ], ), padding: EdgeInsets.only(left: 12.w), height: 62.h, @@ -822,9 +484,17 @@ class _MineShopRecharge extends State { decoration: BoxDecoration( borderRadius: new BorderRadius.only( bottomRight: Radius.circular(6), - topRight: Radius.circular(6), + bottomLeft: Radius.circular(6), ), color: Colors.white, + boxShadow: [ + BoxShadow( + color: (vipCard?.color ?? Color(colorByName(vipCard?.tenantName ?? ""))).withAlpha(10), + offset: Offset(0, 2), + blurRadius: 5, + spreadRadius: 1, + ), + ], ), padding: EdgeInsets.all(12.h), child: Column( diff --git a/lib/mine/mine_view/community_follow.dart b/lib/mine/mine_view/community_follow.dart index 1187727a..12428243 100644 --- a/lib/mine/mine_view/community_follow.dart +++ b/lib/mine/mine_view/community_follow.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/social_info.dart'; import 'package:huixiang/mine/follow_page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_tab.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -39,9 +40,9 @@ class _CommunityFollow extends State ///个人社交信息(粉丝/关注数量/成就数量) querySocialInfo() async { - SharedPreferences value = await SharedPreferences.getInstance(); + apiService = ApiService(Dio(), - context: context, token: value.getString("token"), showLoading: true); + context: context, token: SharedInstance.instance.token, showLoading: true); BaseData? baseData = await apiService?.socialInfo().catchError((onError) {}); diff --git a/lib/mine/mine_view/mine_item.dart b/lib/mine/mine_view/mine_item.dart index d2ce2823..6c49a9bf 100644 --- a/lib/mine/mine_view/mine_item.dart +++ b/lib/mine/mine_view/mine_item.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -138,14 +139,11 @@ class _MineItem extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/coupon_page'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/coupon_page'); }, child: mineItem( S.of(context).youhuiquan, @@ -158,14 +156,11 @@ class _MineItem extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/mine_wallet'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/mine_wallet'); }, child: mineItem( S.of(context).huixiangqianbao, @@ -178,14 +173,11 @@ class _MineItem extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/mine_shop_page'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/mine_shop_page'); }, child: mineItem( S.of(context).dianpuchongzhi, @@ -198,15 +190,11 @@ class _MineItem extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context) - .pushNamed('/router/exchange_history_page'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/exchange_history_page'); }, child: mineItem( S.of(context).duihuanlishi, diff --git a/lib/mine/mine_view/mine_navbar.dart b/lib/mine/mine_view/mine_navbar.dart index 4d536661..ce27c37d 100644 --- a/lib/mine/mine_view/mine_navbar.dart +++ b/lib/mine/mine_view/mine_navbar.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -24,12 +25,13 @@ class _MineNavbar extends State { @override Widget build(BuildContext context) { return Container( - margin: EdgeInsets.fromLTRB( - 13.5.w, 15.h, 13.5.w, 15.h, + margin: EdgeInsets.symmetric( + horizontal: 13.5.w, + vertical: 15.h, ), padding: EdgeInsets.only( - top: 26.h, - bottom: 24.h, + top: 26, + bottom: 24, ), decoration: BoxDecoration( color: Colors.white, @@ -52,15 +54,14 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed( - '/router/order_history_page', - arguments: {"status": 0}); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed( + '/router/order_history_page', + arguments: {"status": 0}, + ); }, child: mineTopItem( S.of(context).dingdan, @@ -73,13 +74,11 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/mine_wallet'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/mine_wallet'); }, child: mineTopItem( S.of(context).qianbao, @@ -92,14 +91,11 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/vip_pay_code'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/vip_pay_code'); }, child: mineTopItem( S.of(context).huiyuanma, @@ -112,14 +108,11 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/setting_page'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/setting_page'); }, child: mineTopItem( S.of(context).shezhi, @@ -165,15 +158,12 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/coupon_page'); - widget.queryCoupon(); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/coupon_page'); + widget.queryCoupon(); }, child: mineBottomItem( widget.couponNum ?? "0", @@ -185,14 +175,11 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - // SharedPreferences.getInstance().then((value) { - // if (value.getString("token") == null || - // value.getString("token") == "") { + // if (SharedInstance.instance.token.isEmpty) { // LoginTipsDialog().show(context); // return; // } // widget.toIntegralPage(); - // }); }, child: mineBottomItem( widget.userInfo?.points ?? "0", @@ -204,20 +191,17 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed( - '/router/communityFollow', - arguments: { - "status":0 - }, - ); - }); - }, + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed( + '/router/communityFollow', + arguments: { + "status":0 + }, + ); + }, child: mineBottomItem( "${widget.infoNumber?.follow ?? "0"}", S.of(context).guanzhu, @@ -228,19 +212,16 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed( - '/router/communityFollow', - arguments: { - "status":1 - }, - ); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed( + '/router/communityFollow', + arguments: { + "status":1 + }, + ); }, child: mineBottomItem( "${widget.infoNumber?.fans ?? "0"}", @@ -252,14 +233,11 @@ class _MineNavbar extends State { Expanded( child: InkWell( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/trading_card_page'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/trading_card_page'); }, child: mineBottomItem( widget.userInfo?.happyBean ?? "0", diff --git a/lib/mine/mine_view/mine_order.dart b/lib/mine/mine_view/mine_order.dart index 78d2d32a..645cb8e2 100644 --- a/lib/mine/mine_view/mine_order.dart +++ b/lib/mine/mine_view/mine_order.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -81,18 +82,16 @@ class _MineOrderView extends State { } toOrderHistory(int status) { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed( - '/router/order_history_page', - arguments: { - "status":status, - }, - ); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed( + '/router/order_history_page', + arguments: { + "status":status, + }, + ); } List orderStatusImg = [ diff --git a/lib/mine/mine_view/mine_view.dart b/lib/mine/mine_view/mine_view.dart index a2c60ed1..186236bf 100644 --- a/lib/mine/mine_view/mine_view.dart +++ b/lib/mine/mine_view/mine_view.dart @@ -69,8 +69,7 @@ class _MineView extends State { margin: EdgeInsets.only(right: 12.w), child: GestureDetector( onTap: () { - Navigator.of(context) - .pushNamed('/router/system_msg_page') + Navigator.of(context).pushNamed('/router/system_msg_page') .then((value) { widget.messageZero(); }); @@ -108,11 +107,14 @@ class _MineView extends State { backgroup: Color(0xFFFF441A), fontSize: 8.sp, radius: 100, - )), - ) + ), + ), + ), ], ), - ))), + ), + ), + ), InkWell( onTap: () { toScan(); @@ -145,9 +147,6 @@ class _MineView extends State { ), ), mineView(), - SizedBox( - height: 12.h, - ), ], ); } @@ -281,7 +280,7 @@ class _MineView extends State { Expanded( flex: 1, child: Container( - height: 53.h, + height: 60, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -421,15 +420,13 @@ class _MineView extends State { } Widget mineVip(){ - return Container( - child: MineVipEntry( - tag: "vip", - ranks: widget.ranks, - userInfo: widget.userInfo, - rank: int.tryParse("${widget.userInfo?.expendAmount}") ?? 0, - rankMax: widget.userInfo?.memberRankVo?.nextOrigin ?? 0, - createTime: widget.userInfo?.createTime ?? "", - ), + return MineVipEntry( + tag: "vip", + ranks: widget.ranks, + userInfo: widget.userInfo, + rank: int.tryParse("${widget.userInfo?.expendAmount}") ?? 0, + rankMax: widget.userInfo?.memberRankVo?.nextOrigin ?? 0, + createTime: widget.userInfo?.createTime ?? "", ); } } diff --git a/lib/mine/mine_view/wallet_coupon_view.dart b/lib/mine/mine_view/wallet_coupon_view.dart index d3958933..12e6c1cb 100644 --- a/lib/mine/mine_view/wallet_coupon_view.dart +++ b/lib/mine/mine_view/wallet_coupon_view.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -33,14 +34,11 @@ class _WalletCoupon extends State { child: (Theme.of(context).platform == TargetPlatform.android) ? GestureDetector( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/roll_center_page'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/roll_center_page'); }, child: Row( children: [ @@ -88,15 +86,11 @@ class _WalletCoupon extends State { flex: 1, child: GestureDetector( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context) - .pushNamed('/router/roll_center_page'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/roll_center_page'); }, child: Row( mainAxisAlignment: MainAxisAlignment.center, @@ -136,14 +130,11 @@ class _WalletCoupon extends State { flex: 1, child: GestureDetector( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - Navigator.of(context).pushNamed('/router/mine_wallet'); - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/mine_wallet'); }, child: Row( mainAxisAlignment: MainAxisAlignment.center, diff --git a/lib/mine/mine_vip/binding_assistant_card.dart b/lib/mine/mine_vip/binding_assistant_card.dart index f93765f3..9688d7c0 100644 --- a/lib/mine/mine_vip/binding_assistant_card.dart +++ b/lib/mine/mine_vip/binding_assistant_card.dart @@ -5,6 +5,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -28,22 +29,17 @@ class _BindingAssistantCard extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, token: value.getString('token')), - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); } ///绑定副卡 queryBindSecondCard(phone) async { BaseData? baseData = await apiService?.bindSecondCard(phone).catchError((onError) { - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { SmartDialog.showToast("绑定成功", alignment: Alignment.center); Navigator.of(context).pop(true); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } diff --git a/lib/mine/mine_vip/legal_right_details.dart b/lib/mine/mine_vip/legal_right_details.dart index 25da410a..8d6834b1 100644 --- a/lib/mine/mine_vip/legal_right_details.dart +++ b/lib/mine/mine_vip/legal_right_details.dart @@ -12,6 +12,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -41,18 +42,15 @@ class _LegalRightDetails extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), context: context, token: value.getString("token")); - }); + apiService = + ApiService(Dio(), context: context, token: SharedInstance.instance.token); vipBenefitList.addAll(widget.arguments?["vipBenefitList"] ?? []); querySecondCardList(); } ///副卡列表 querySecondCardList() async { - BaseListData? baseData = - await apiService?.secondCardList().catchError((onError) { + BaseListData? baseData = await apiService?.secondCardList().catchError((onError) { return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { diff --git a/lib/mine/mine_vip/mine_attainment_page.dart b/lib/mine/mine_vip/mine_attainment_page.dart index 7c929350..b1ef323c 100644 --- a/lib/mine/mine_vip/mine_attainment_page.dart +++ b/lib/mine/mine_vip/mine_attainment_page.dart @@ -12,6 +12,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/badge_attainment_dialog.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; @@ -93,16 +94,17 @@ class _MineAttainmentPage extends State { ///个人社交信息(粉丝/关注数量/成就数量) querySocialInfo() async { - SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService( Dio(), context: context, - token: value.getString("token"), + token: SharedInstance.instance.token, showLoading: false, ); BaseData? baseData = - await apiService?.socialInfo().catchError((onError) {}); + await apiService?.socialInfo().catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { infoNumber = baseData?.data; diff --git a/lib/mine/mine_vip/mine_vip_core.dart b/lib/mine/mine_vip/mine_vip_core.dart index 7712f4c3..ccdd4370 100644 --- a/lib/mine/mine_vip/mine_vip_core.dart +++ b/lib/mine/mine_vip/mine_vip_core.dart @@ -15,6 +15,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/vip_dialog.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -52,28 +53,14 @@ class _MineVipCore extends State { void initState() { super.initState(); userInfo = widget.arguments["userInfo"]; - SharedPreferences.getInstance().then((value) { - // if (widget.arguments["rankLevel"] == 1 && - // !(value.getBool("FirstYinKa") ?? false)) { - // showAlertDialog("银卡会员"); - // value.setBool("FirstYinKa", true); - // } else if (widget.arguments["rankLevel"] == 2 && - // !(value.getBool("FirstJinKa") ?? false)) { - // showAlertDialog("金卡会员"); - // value.setBool("FirstJinKa", true); - // } else if (widget.arguments["rankLevel"] == 3 && - // !(value.getBool("FirstGongC") ?? false)) { - // showAlertDialog("共创会员"); - // value.setBool("FirstGongC", true); - // } - apiService = ApiService(Dio(), - context: context, - showLoading: false, - token: value.getString("token")); - queryVipLevel(); - queryBenefitList(); - queryRuleDetails(); - }); + apiService = ApiService(Dio(), + context: context, + showLoading: false, + token: SharedInstance.instance.token, + ); + queryVipLevel(); + queryBenefitList(); + queryRuleDetails(); fluwx.addSubscriber((event) async { print("payCallback: ${event.errCode}"); if (event.errCode == 0) { diff --git a/lib/mine/mine_vip_level_page.dart b/lib/mine/mine_vip_level_page.dart index a072cd50..c9f1739f 100644 --- a/lib/mine/mine_vip_level_page.dart +++ b/lib/mine/mine_vip_level_page.dart @@ -8,6 +8,7 @@ import 'package:huixiang/data/rank.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/mine_vip_view.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -33,25 +34,20 @@ class _MineVipLevelPage extends State { @override void initState() { super.initState(); - - SharedPreferences.getInstance().then((value) { - apiService = ApiService(Dio(), context: context, token: value.getString("token")); - queryVipLevel(); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryVipLevel(); } queryVipLevel() async { BaseListData? rankData = await apiService?.rankList().catchError((onError) { - return Future.value(null); + return BaseListData()..isSuccess = false; }); if (rankData?.isSuccess ?? false) { ranks.clear(); ranks.addAll(rankData!.data ?? []); setState(() { - controller.move((widget.arguments?["rankLevel"] - 1), animation: false); + controller.move((widget.arguments["rankLevel"] - 1), animation: false); }); - } else { - SmartDialog.showToast("${rankData?.msg}", alignment: Alignment.center); } } diff --git a/lib/mine/mine_wallet_page.dart b/lib/mine/mine_wallet_page.dart index fff01b6d..335cb581 100644 --- a/lib/mine/mine_wallet_page.dart +++ b/lib/mine/mine_wallet_page.dart @@ -10,6 +10,7 @@ import 'package:huixiang/data/user_bill.dart'; import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -48,10 +49,9 @@ class _MineWalletPage extends State { List userBills = []; loadBalance() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - String? user = sharedPreferences.getString('user'); - if (user?.isNotEmpty ?? false) { - userInfo = UserInfo.fromJson(jsonDecode(user!)); + String user = SharedInstance.instance.userJson; + if (user.isNotEmpty) { + userInfo = UserInfo.fromJson(jsonDecode(user)); } mgreenMoney = double.tryParse("${userInfo?.greenMoney}"); mRaiseMoney = double.tryParse("${userInfo?.raiseMoney}"); @@ -59,7 +59,8 @@ class _MineWalletPage extends State { pBalance = mBalance + mgreenMoney; activityMoney = double.tryParse("${userInfo?.activityMoney}"); if (mounted) setState(() {}); - String? token = sharedPreferences.getString("token"); + + String token = SharedInstance.instance.token; apiService = ApiService(Dio(), context: context, token: token); loadBillInfo(); } @@ -185,7 +186,9 @@ class _MineWalletPage extends State { child: Column( children: [ Padding( - padding: EdgeInsets.only(top: 18.h, bottom: 6.h), + padding: EdgeInsets.only( + top: 18.h, bottom: 6.h, + ), child: Text( S.of(context).zongzichanyuan, style: TextStyle( @@ -236,14 +239,15 @@ class _MineWalletPage extends State { Row( children: [ Expanded( - child: Text( - "${S.of(context).yue}(含活动)", - style: TextStyle( - fontSize: 14.sp, - fontWeight: MyFontWeight.semi_bold, - color: Colors.white, + child: Text( + "${S.of(context).yue}(含活动)", + style: TextStyle( + fontSize: 14.sp, + fontWeight: MyFontWeight.semi_bold, + color: Colors.white, + ), ), - )), + ), Text( "${NP.strip(mBalance)}", style: TextStyle( @@ -252,7 +256,7 @@ class _MineWalletPage extends State { fontWeight: MyFontWeight.medium, color: Colors.white, ), - ) + ), ], ), Container( @@ -266,14 +270,15 @@ class _MineWalletPage extends State { Row( children: [ Expanded( - child: Text( - "赠送余额", - style: TextStyle( - fontSize: 14.sp, - fontWeight: MyFontWeight.semi_bold, - color: Colors.white, + child: Text( + "赠送余额", + style: TextStyle( + fontSize: 14.sp, + fontWeight: MyFontWeight.semi_bold, + color: Colors.white, + ), ), - )), + ), Text( "${NP.strip(activityMoney)}", style: TextStyle( @@ -314,7 +319,7 @@ class _MineWalletPage extends State { fontWeight: MyFontWeight.medium, color: Colors.white, ), - ) + ), ], ), if (mgreenMoney != 0) @@ -352,16 +357,16 @@ class _MineWalletPage extends State { height: 16.h, ), Expanded( - child: Text( - integralTips ? " 有效期至${userInfo?.raiseExpireTime?.split(" ")[0]}" : "", - style: TextStyle( - fontSize: 10.sp, - fontFamily: 'JDZhengHT', - fontWeight: MyFontWeight.light, - color: Colors.white, + child: Text( + integralTips ? " 有效期至${userInfo?.raiseExpireTime?.split(" ")[0]}" : "", + style: TextStyle( + fontSize: 10.sp, + fontFamily: 'JDZhengHT', + fontWeight: MyFontWeight.light, + color: Colors.white, + ), ), ), - ), Text( "${NP.strip(mRaiseMoney)}", style: TextStyle( @@ -370,7 +375,7 @@ class _MineWalletPage extends State { fontWeight: MyFontWeight.medium, color: Colors.white, ), - ) + ), ], ), ), @@ -394,18 +399,24 @@ class _MineWalletPage extends State { Widget balanceHistory() { return Container( - margin: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 0), - padding: EdgeInsets.fromLTRB(24.w, 24.h, 24.w, 24.h), + margin: EdgeInsets.fromLTRB( + 16.w, 16.h, 16.w, 0, + ), + padding: EdgeInsets.fromLTRB( + 24.w, 24.h, 24.w, 24.h, + ), decoration: BoxDecoration( color: Colors.white, - borderRadius: BorderRadius.all(Radius.circular(8)), + borderRadius: BorderRadius.all( + Radius.circular(8), + ), boxShadow: [ BoxShadow( color: Colors.black.withAlpha(25), offset: Offset(0, 3), blurRadius: 14, spreadRadius: 0, - ) + ), ], ), child: Column( @@ -433,7 +444,7 @@ class _MineWalletPage extends State { margin: EdgeInsets.only(top: 120.h), ) : ListView.builder( - itemCount: userBills.length ?? 0, + itemCount: userBills.length, shrinkWrap: true, padding: EdgeInsets.only(bottom: 20.h), physics: NeverScrollableScrollPhysics(), @@ -458,14 +469,14 @@ class _MineWalletPage extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( - flex: 7, - child: Text( - userBill.type ?? "", - style: TextStyle( - color: Colors.black, - fontSize: 12.sp, - ), + flex: 7, + child: Text( + userBill.type ?? "", + style: TextStyle( + color: Colors.black, + fontSize: 12.sp, ), + ), ), Expanded( flex: 4, @@ -498,8 +509,7 @@ class _MineWalletPage extends State { fontSize: 12.sp, ), ), - ) - .toList(), + ).toList(), ), ), ], @@ -547,8 +557,7 @@ class _MineWalletPage extends State { fontSize: 12.sp, ), ), - ) - .toList(), + ).toList(), ), ), ], @@ -600,8 +609,7 @@ class _MineWalletPage extends State { fontSize: 12.sp, ), ), - ) - .toList(), + ).toList(), ), ), ], @@ -672,8 +680,6 @@ class _MineWalletPage extends State { } } - //assets/image/recharge,Btn.png - toRecharge() async { await Navigator.of(context).pushNamed('/router/recharge_page'); loadBillInfo(); diff --git a/lib/mine/personal_page.dart b/lib/mine/personal_page.dart index 144fee7b..2c2c02a2 100644 --- a/lib/mine/personal_page.dart +++ b/lib/mine/personal_page.dart @@ -7,6 +7,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:huixiang/community/community_view/community_dynamic.dart'; import 'package:huixiang/community/photo_view_gallery_screen.dart'; +import 'package:huixiang/data/im_user.dart'; import 'package:huixiang/data/member_infor.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/article.dart'; @@ -17,10 +18,12 @@ import 'package:huixiang/data/upload_result.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; +import 'package:huixiang/view_widget/settlement_tips_dialog.dart'; import 'package:image_pickers/image_pickers.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -53,18 +56,21 @@ class _PersonalPage extends State with WidgetsBindingObserver { String? memberId; Map modifyInfo = {"background": ""}; + String? selfUserId; + @override void initState() { super.initState(); memberId = widget.arguments?["memberId"]; WidgetsBinding.instance.addObserver(this); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, - token: value.getString('token'), - showLoading: true), - _onRefresh(), - }); + + selfUserId = SharedInstance.instance.userId; + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: true, + ); + _onRefresh(); } _onRefresh() async { @@ -74,10 +80,15 @@ class _PersonalPage extends State with WidgetsBindingObserver { ///查询会员信息 queryMember(id) async { + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); BaseData? baseData = await apiService?.memberDetail(id).catchError((error) { refreshController.refreshFailed(); - debugPrint("${error}"); - return Future.value(null); + debugPrint(error); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { @@ -89,6 +100,23 @@ class _PersonalPage extends State with WidgetsBindingObserver { } } + ///关注/取关会员 + vipFollow(followId, isFollow) async { + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + BaseData? baseData = await apiService?.follow(followId ?? ""); + if (baseData?.isSuccess ?? false) { + queryCommunity(null); + SmartDialog.show(builder: (BuildContext context) { + return SettlementTips(() {}, text: isFollow ? "取关成功" : "关注成功"); + }); + setState(() {}); + } + } + ///动态列表 queryCommunity(String? searchKey) async { if (!isRefresh) { @@ -99,11 +127,17 @@ class _PersonalPage extends State with WidgetsBindingObserver { return; } isLoadingData = true; + userId = SharedInstance.instance.userId; + apiService ??= ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); if (isLoadMore) { pageNum += 1; isLoadMore = false; } else if (searchKey == null) pageNum = 1; - BaseData>? baseData = await apiService?.trendList({ + BaseData>? baseData = + await apiService?.trendList({ "mid": memberId == "0" ? userId : memberId, "onlyFollow": false, "onlyMe": true, @@ -111,40 +145,76 @@ class _PersonalPage extends State with WidgetsBindingObserver { "pageSize": 10, "searchKey": searchKey ?? "" }).catchError((error) { - debugPrint("${error}"); - return Future.value(null); + debugPrint(error); + if (searchKey == null) { + refreshController.refreshFailed(); + refreshController.loadFailed(); + } + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { - if (baseData!.data?.list?.isNotEmpty ?? false) - articles.forEach((element) { - if (element.id == searchKey) { - element.content = jsonEncode(baseData.data!.list![0].subjectInfo); - element.mainTitle = baseData.data!.list![0].subject; - element.followed = baseData.data!.list![0].selfFollow; - element.liked = baseData.data!.list![0].selfLike; - element.authorHeadImg = baseData.data!.list![0].memberInfo?.avatar; - element.authorName = baseData.data!.list![0].memberInfo?.nickname; - element.location = baseData.data!.list![0].location; - element.createTime = baseData.data!.list![0].createTime; - element.author = baseData.data!.list![0].memberInfo?.mid; - element.viewers = baseData.data!.list![0].viewers; - element.likes = baseData.data!.list![0].likes; - element.comments = baseData.data!.list![0].comments; - this.isRefresh = false; - setState(() {}); + if (baseData!.data?.list?.isNotEmpty ?? false) { + if (searchKey != null) { + articles.forEach((element) { + if (element.id == searchKey) { + element.content = jsonEncode(baseData.data!.list![0].subjectInfo); + element.mainTitle = baseData.data!.list![0].subject; + element.followed = baseData.data!.list![0].selfFollow; + element.liked = baseData.data!.list![0].selfLike; + element.authorHeadImg = baseData.data!.list![0].memberInfo?.avatar; + element.authorName = baseData.data!.list![0].memberInfo?.nickname; + element.location = baseData.data!.list![0].location; + element.createTime = baseData.data!.list![0].createTime; + element.author = baseData.data!.list![0].memberInfo?.mid; + element.viewers = baseData.data!.list![0].viewers; + element.likes = baseData.data!.list![0].likes; + element.comments = baseData.data!.list![0].comments; + this.isRefresh = false; + setState(() {}); + } + }); + } else { + if (pageNum == 1) { + articles.clear(); + } + baseData.data?.list?.forEach((element) { + var article = Article(); + article.id = element.id; + article.content = jsonEncode(element.subjectInfo); + article.mainTitle = element.subject; + article.followed = element.selfFollow; + article.liked = element.selfLike; + article.authorHeadImg = element.memberInfo?.avatar; + article.authorName = element.memberInfo?.nickname; + article.location = element.location; + article.createTime = element.createTime; + article.author = element.memberInfo?.mid; + article.viewers = element.viewers; + article.likes = element.likes; + article.comments = element.comments; + articles.add(article); + }); + setState(() {}); + // comments.sort((a,b)=>b.createTime.compareTo(a.createTime)); + // print("comments: ${comments.length}"); + if ((int.tryParse(baseData.data?.total ?? "0") ?? 0) < (pageNum * 10)) { + refreshController.loadNoData(); } - }); } + } + + } isLoadingData = false; } ///去编辑个人资料 _toUserInfo() async { - SharedPreferences shared = await SharedPreferences.getInstance(); - if (shared.getString("token") == null || shared.getString("token") == "") { - Navigator.of(context) - .pushNamed('/router/new_login_page', arguments: {"login": "login"}); + if (SharedInstance.instance.token.isEmpty) { + Navigator.of(context).pushNamed( + '/router/new_login_page', + arguments: {"login": "login"}, + ); return; } await Navigator.of(context) @@ -159,39 +229,40 @@ class _PersonalPage extends State with WidgetsBindingObserver { ///显示图片选择方式 showImagePicker() { showCupertinoModalPopup( - context: context, - builder: (contetx) { - return CupertinoActionSheet( - title: Text(S.of(context).genghuantouxiang), - actions: [ - CupertinoActionSheetAction( - child: Text(S.of(context).paizhao), - onPressed: () { - openCamera(); - Navigator.of(context).pop(); - }, - isDefaultAction: true, - isDestructiveAction: false, - ), - CupertinoActionSheetAction( - child: Text(S.of(context).xiangce), - onPressed: () { - openStorage(); - Navigator.of(context).pop(); - }, - isDefaultAction: true, - isDestructiveAction: false, - ), - ], - cancelButton: CupertinoActionSheetAction( + context: context, + builder: (context) { + return CupertinoActionSheet( + title: Text(S.of(context).genghuantouxiang), + actions: [ + CupertinoActionSheetAction( + child: Text(S.of(context).paizhao), + onPressed: () { + openCamera(); + Navigator.of(context).pop(); + }, + isDefaultAction: true, + isDestructiveAction: false, + ), + CupertinoActionSheetAction( + child: Text(S.of(context).xiangce), onPressed: () { + openStorage(); Navigator.of(context).pop(); }, - child: Text(S.of(context).quxiao), - isDestructiveAction: true, + isDefaultAction: true, + isDestructiveAction: false, ), - ); - }); + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text(S.of(context).quxiao), + isDestructiveAction: true, + ), + ); + }, + ); } ///拍照 @@ -245,7 +316,7 @@ class _PersonalPage extends State with WidgetsBindingObserver { ///调用修改用户信息接口 modifyInfos() async { var info = await apiService?.editInfo(modifyInfo).catchError((onError) { - return Future.value(null); + return BaseData()..isSuccess = false; }); if (info?.isSuccess ?? false) { setState(() { @@ -258,10 +329,11 @@ class _PersonalPage extends State with WidgetsBindingObserver { ///文件上传 fileUpload() async { if ((filePath?.isNotEmpty ?? false) && await File(filePath!).exists()) { - BaseData? baseData = await apiService?.upload(File(filePath!), 123123123, false) + BaseData? baseData = await apiService + ?.upload(File(filePath!), 123123123, false) .catchError((onError) { - return Future.value(null); - }); + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { UploadResult? uploadResult = baseData!.data; modifyInfo["background"] = uploadResult?.url; @@ -274,431 +346,730 @@ class _PersonalPage extends State with WidgetsBindingObserver { Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, - body:SmartRefresher( - controller: refreshController, - enablePullDown: true, - enablePullUp: (articles.length == 0) ? false: true, - header: MyHeader(), - footer: CustomFooter( - builder: (context, mode) { - return MyFooter(mode); - }, - ), - onRefresh: _onRefresh, - onLoading: () { - isLoadMore = true; - setState(() { - _onRefresh(); - }); + body: SmartRefresher( + controller: refreshController, + enablePullDown: true, + enablePullUp: (articles.length == 0) ? false : true, + header: MyHeader(), + footer: CustomFooter( + builder: (context, mode) { + return MyFooter(mode); }, + ), + onRefresh: _onRefresh, + onLoading: () { + isLoadMore = true; + setState(() { + _onRefresh(); + }); + }, + physics: BouncingScrollPhysics(), + scrollController: scrollController, + child: SingleChildScrollView( physics: BouncingScrollPhysics(), - scrollController: scrollController, - child: SingleChildScrollView( - physics: BouncingScrollPhysics(), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.start, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Stack( children: [ Container( - height: 248.h, - color: Color(0xFFFFFFFF), - // color: Colors.red, - child: Stack( - // alignment: Alignment.bottomLeft, - children: [ - Positioned( - top: 0, - left: 0, - bottom: 36.h, - right: 0, - child: Stack( - alignment: Alignment.bottomRight, - children: [ - Container( - color: Colors.black, - child: Opacity( - opacity: 0.9, - child: MImage( - memberInfor?.background ?? "", - width: double.infinity, - height: 260.h, - fit: BoxFit.cover, - errorSrc: "assets/image/default_1.webp", - fadeSrc: "assets/image/default_1.webp", - ), - ), - ), - Container( - margin: EdgeInsets.only( - top: 50.h, left: 16.w, right: 16.w, - ), - alignment: Alignment.topLeft, - decoration: BoxDecoration( - color: Colors.transparent, - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - GestureDetector( - child: Image.asset( - "assets/image/integral_return.webp", - width: 24, - height: 24, - ), - onTap: () { - Navigator.of(context).pop(); - }, - ), - ], - ), - ), - if (memberId == "0") - Positioned( - bottom: 9.h, - right: 16.w, - child: GestureDetector( - onTap: () { - showImagePicker(); - }, - child: Container( - padding: EdgeInsets.only(left: 2, right: 2), - width: 59.w, - height: 23.h, - alignment: Alignment.center, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(2), - color: Color(0x80000000), - ), - child: Text( - S.of(context).genghuanbeijing, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 12.sp, - fontWeight: MyFontWeight.regular, - color: Color(0xFFFFFFFF), - ), - ), - ), - ), - ), - ], + color: Colors.black, + child: Opacity( + opacity: 0.9, + child: MImage( + memberInfor?.background ?? "", + width: double.infinity, + height: 210.h, + fit: BoxFit.cover, + errorSrc: "assets/image/default_1.webp", + fadeSrc: "assets/image/default_1.webp", + ), + ), + ), + Positioned( + top: MediaQuery.of(context).padding.top + 20.h, + left: 17.w, + child: GestureDetector( + child: Image.asset( + "assets/image/integral_return.webp", + width: 24, + height: 24, + ), + onTap: () { + Navigator.of(context).pop(); + }, + ), + ), + if (memberId == "0") + Positioned( + bottom: 9.h, + right: 16.w, + child: GestureDetector( + onTap: () { + showImagePicker(); + }, + child: Container( + padding: EdgeInsets.only(left: 2, right: 2), + width: 59.w, + height: 23.h, + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(2), + color: Color(0x80000000), + ), + child: Text( + S.of(context).genghuanbeijing, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + color: Color(0xFFFFFFFF), + ), ), ), - homeInfo(), - ], + ), ), + ], + ), + Container( + // margin: EdgeInsets.only(bottom: 30.h), + decoration: BoxDecoration( + color: Color(0xFFFFFFFF), + borderRadius: BorderRadius.only( + topRight: Radius.circular(12), + topLeft: Radius.circular(12), ), - Container( - color: Color(0xFFFFFFFF), - margin: EdgeInsets.only(bottom: 30.h), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - margin: EdgeInsets.only( - left: 86.w, top: 12.h, right: 16.w, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + trendsInfo(), + Padding( + padding: EdgeInsets.only( + left: 16, + top: 16, + bottom: 16, + ), + child: Text( + memberId != selfUserId ? "TA的动态" : "我的动态", + style: TextStyle( + color: Color(0xFF353535), + fontSize: 15.sp, + fontWeight: MyFontWeight.semi_bold, + ), + ), + ), + dynamicList(), + ], + ), + ), + ], + ), + ), + ), + ); + } + + ///个人信息 + Widget homeInfo() { + return Positioned( + top: 0, + bottom: 0, + left: 0, + right: 0, + child: Container( + padding: EdgeInsets.only( + left: 16.w, + right: 16.w, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + GestureDetector( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PhotoViewGalleryScreen( + images: [ + (memberInfor?.headimg ?? "").isEmpty + ? "https://i.postimg.cc/Pq6vjfnw/default-1.webp" + : memberInfor?.headimg + ], //传入图片list + index: 0, //传入当前点击的图片的index + ), + ), + ); + }, + child: MImage( + memberInfor?.headimg ?? "", + isCircle: true, + width: 66.h, + height: 66.h, + fit: BoxFit.cover, + errorSrc: "assets/image/default_user.webp", + fadeSrc: "assets/image/default_user.webp", + ), + ), + SizedBox(width: 10.w), + Text( + memberInfor?.nickname ?? "回乡", + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 16.sp, + fontWeight: MyFontWeight.medium, + color: Color(0xFF353535), + ), + ), + SizedBox(width: 4.w), + Image.asset( + "assets/image/vip_yk.webp", + width: 20, + height: 20, + ), + Spacer(), + if (memberId == "0") + GestureDetector( + onTap: () { + setState(() { + _toUserInfo(); + }); + }, + child: Container( + height: 23.h, + padding: EdgeInsets.only( + left: 6.w, + right: 6.w, + bottom: 2.h, + top: 2.h, + ), + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(100), + border: Border.all( + width: 1.w, + color: Color(0xFF353535), + style: BorderStyle.solid, + ), + ), + child: Text( + S.of(context).bianjigerenziliao, + style: TextStyle( + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + color: Color(0xFF353535), + ), + ), + ), + ), + if (memberId != selfUserId) + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + if (memberInfor?.id == selfUserId) { + SmartDialog.showToast( + "不能跟自己聊天", + alignment: Alignment.center, + ); + return; + } + Navigator.of(context).pushNamed( + '/router/chat_details_page', + arguments: { + "toUser": ImUser( + avatar: memberInfor?.headimg, + mid: memberInfor?.id, + nickname: memberInfor?.nickname, + ), + }, + ); + }, + child: Container( + padding: EdgeInsets.symmetric( + horizontal: 16.w, + vertical: 3.h, + ), + margin: EdgeInsets.only(right: 8.w), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(100), + border: Border.all( + width: 1, + color: Color(0xFF32A060), + style: BorderStyle.solid, + ), + color: Colors.white, + ), + child: Text( + "私信", + style: TextStyle( + fontSize: 12.sp, + color: Color(0xFF32A060), + fontWeight: MyFontWeight.regular, + ), + ), + ), + ), + if (memberId != selfUserId) + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + setState(() { + vipFollow( + memberId, + (articles.isNotEmpty && + (articles.first.followed ?? false))); + }); + }, + child: Container( + padding: EdgeInsets.symmetric( + horizontal: 16.w, + vertical: 3.5.h, + ), + margin: EdgeInsets.only(right: 8.w), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(100), + color: (articles.isNotEmpty && + (articles.first.followed ?? false)) + ? Color(0xFFE6E6E6) + : Color(0xFF32A060), + ), + child: Text( + (articles.isNotEmpty && (articles.first.followed ?? false)) + ? S.of(context).yiguanzhu + : S.of(context).guanzhu, + style: TextStyle( + fontSize: 12.sp, + color: (articles.isNotEmpty && + (articles.first.followed ?? false)) + ? Color(0xFF808080) + : Colors.white, + fontWeight: MyFontWeight.regular, + ), + ), + ), + ), + ], + ), + ), + ); + } + + ///个人信息 + Widget trendsInfo() { + return Container( + color: Colors.white, + margin: EdgeInsets.only( + top: 16, + left: 16, + right: 16, + ), + child: Column( + children: [ + ///个人信息 + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GestureDetector( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PhotoViewGalleryScreen( + images: [ + (memberInfor?.headimg ?? "").isEmpty + ? "https://i.postimg.cc/Pq6vjfnw/default-1.webp" + : memberInfor?.headimg + ], //传入图片list + index: 0, //传入当前点击的图片的index + ), + ), + ); + }, + child: MImage( + memberInfor?.headimg ?? "", + isCircle: true, + width: 69, + height: 69, + fit: BoxFit.cover, + errorSrc: "assets/image/default_user.webp", + fadeSrc: "assets/image/default_user.webp", + ), + ), + Expanded( + child: Container( + padding: EdgeInsets.only(left: 10), + height: 69, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Row( + children: [ + Text( + memberInfor?.nickname ?? "回乡", + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 16.sp, + fontWeight: MyFontWeight.medium, + color: Color(0xFF353535), ), - child: GestureDetector( + ), + SizedBox(width: 4.w), + Image.asset( + "assets/image/vip_yk.webp", + width: 20, + height: 20, + ), + Spacer(), + if (memberId == "0") + GestureDetector( onTap: () { setState(() { - isShrink = !isShrink; + _toUserInfo(); }); }, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Expanded( - flex: 1, - child: Text( - memberId == "0" - ? ((memberInfor?.signature == "") - ? "还未编辑个性签名~" - : memberInfor?.signature ?? "") - : "个性签名: ${(memberInfor?.signature == "") ? "还未编辑个性签名~" : memberInfor?.signature ?? ""}", - overflow: isShrink - ? TextOverflow.visible - : TextOverflow.ellipsis, - maxLines: isShrink ? 10 : 2, - style: TextStyle( - fontSize: 12.sp, - color: Color(0xFF868686), - fontWeight: MyFontWeight.regular, - height: 1.5.h, - ), - ), - ), - Icon( - (!isShrink) - ? Icons.chevron_right - : Icons.keyboard_arrow_up, - color: Colors.black, - size: 18, - ), - ], - ), - )), - Container( - margin: EdgeInsets.only( - left: 16.w, right: 16.w, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () {}, - child: Container( - color: Colors.transparent, - padding: EdgeInsets.all(16), - child: Column( - children: [ - Text( - "${memberInfor?.follow ?? 0}", - style: TextStyle( - color: Color(0xFF353535), - fontSize: 16.sp, - fontWeight: MyFontWeight.semi_bold, - ), - ), - SizedBox( - height: 4.h, - ), - Text( - S.of(context).guanzhu, - style: TextStyle( - color: Color(0xFF353535), - fontSize: 12.sp, - fontWeight: MyFontWeight.regular, - ), - ), - ], - ), + child: Container( + height: 23.h, + padding: EdgeInsets.only( + left: 6.w, + right: 6.w, + bottom: 2.h, + top: 2.h, + ), + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(100), + border: Border.all( + width: 1.w, + color: Color(0xFF353535), + style: BorderStyle.solid, ), ), - ), - Expanded( - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () {}, - child: Container( - color: Colors.transparent, - padding: EdgeInsets.all(16), - child: Column( - children: [ - Text( - "${memberInfor?.fans ?? 0}", - style: TextStyle( - color: Color(0xFF353535), - fontSize: 16.sp, - fontWeight: MyFontWeight.semi_bold, - ), - ), - SizedBox( - height: 4.h, - ), - Text( - S.of(context).fensi, - style: TextStyle( - color: Color(0xFF353535), - fontSize: 12.sp, - fontWeight: MyFontWeight.regular, - ), - ), - ], - ), + child: Text( + S.of(context).bianjigerenziliao, + style: TextStyle( + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + color: Color(0xFF353535), ), ), ), + ), + ], + ), + Container( + child: GestureDetector( + onTap: () { + setState(() { + isShrink = !isShrink; + }); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ Expanded( - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () {}, - child: Container( - color: Colors.transparent, - padding: EdgeInsets.all(16), - child: Column( - children: [ - Text( - "${memberInfor?.trendTotal ?? 0}", - style: TextStyle( - color: Color(0xFF353535), - fontSize: 16.sp, - fontWeight: MyFontWeight.semi_bold, - ), - ), - SizedBox( - height: 4.h, - ), - Text( - S.of(context).dongtai, - style: TextStyle( - color: Color(0xFF353535), - fontSize: 12.sp, - fontWeight: MyFontWeight.regular, - ), - ), - ], - ), + flex: 1, + child: Text( + memberId == "0" + ? ((memberInfor?.signature == "") + ? "还未编辑个性签名~" + : memberInfor?.signature ?? "") + : "个性签名: ${(memberInfor?.signature == "") ? "还未编辑个性签名~" : memberInfor?.signature ?? ""}", + overflow: isShrink + ? TextOverflow.visible + : TextOverflow.ellipsis, + maxLines: isShrink ? 10 : 2, + style: TextStyle( + fontSize: 12.sp, + color: Color(0xFF868686), + fontWeight: MyFontWeight.regular, + height: 1.5.h, ), ), ), - Expanded( - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () {}, - child: Container( - color: Colors.transparent, - padding: EdgeInsets.all(16), - child: Column( - children: [ - Text( - "${memberInfor?.gainLikeTotal ?? 0}", - style: TextStyle( - color: Color(0xFF353535), - fontSize: 16.sp, - fontWeight: MyFontWeight.semi_bold, - ), - ), - SizedBox( - height: 4.h, - ), - Text( - S.of(context).huozan, - style: TextStyle( - color: Color(0xFF353535), - fontSize: 12.sp, - fontWeight: MyFontWeight.regular, - ), - ), - ], - )), - ), + Icon( + (!isShrink) + ? Icons.keyboard_arrow_down + : Icons.keyboard_arrow_up, + color: Colors.black, + size: 18, ), ], ), ), - Container( - margin: EdgeInsets.all(16), - height: 1.h, - color: Color(0xFFF7F7F7), + ), + ], + ), + ), + ), + ], + ), + ///关注,粉丝,动态,获赞,好友数量 + Container( + margin: EdgeInsets.only( + top: 16, + bottom: 16, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () {}, + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + "${memberInfor?.follow ?? 0}", + style: TextStyle( + color: Color(0xFF353535), + fontSize: 16.sp, + fontWeight: MyFontWeight.semi_bold, + ), + ), + SizedBox( + height: 4.h, + ), + Text( + S.of(context).guanzhu, + style: TextStyle( + color: Color(0xFF353535), + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + ), ), - Padding( - padding: EdgeInsets.only(left: 16.w), - child: Text( - memberId != "0" ? "TA的动态" : "我的动态", - style: TextStyle( - color: Color(0xFF353535), - fontSize: 15.sp, - fontWeight: MyFontWeight.semi_bold, - ), - )), - dynamicList(), ], ), ), - ], - )), - ) - ); - } - - Widget homeInfo() { - return Positioned( - top: 0, - bottom: 0, - left: 0, - right: 0, - child: Container( - padding: EdgeInsets.only( - left: 16.w, - right: 16.w, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - GestureDetector( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PhotoViewGalleryScreen( - images: [ - memberInfor?.headimg ?? "https://i.postimg.cc/Pq6vjfnw/default-1.webp" - ], //传入图片list - index: 0, //传入当前点击的图片的index + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + "${memberInfor?.fans ?? 0}", + style: TextStyle( + color: Color(0xFF353535), + fontSize: 16.sp, + fontWeight: MyFontWeight.semi_bold, ), - )); - }, - child: MImage( - memberInfor?.headimg ?? "", - isCircle: true, - width: 66, - height: 66, - fit: BoxFit.cover, - errorSrc: "assets/image/default_user.webp", - fadeSrc: "assets/image/default_user.webp", + ), + SizedBox( + height: 4.h, + ), + Text( + S.of(context).fensi, + style: TextStyle( + color: Color(0xFF353535), + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + ), + ), + ], + ), ), - ), - SizedBox(width: 10.w), - Text( - memberInfor?.nickname ?? "回乡", - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 16.sp, - fontWeight: MyFontWeight.medium, - color: Color(0xFF353535), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + (memberInfor?.trendTotal ?? 0).toString(), + style: TextStyle( + color: Color(0xFF353535), + fontSize: 16.sp, + fontWeight: MyFontWeight.semi_bold, + ), + ), + SizedBox( + height: 4.h, + ), + Text( + S.of(context).dongtai, + style: TextStyle( + color: Color(0xFF353535), + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + ), + ), + ], + ), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + (memberInfor?.gainLikeTotal ?? 0).toString(), + style: TextStyle( + color: Color(0xFF353535), + fontSize: 16.sp, + fontWeight: MyFontWeight.semi_bold, + ), + ), + SizedBox( + height: 4.h, + ), + Text( + S.of(context).huozan, + style: TextStyle( + color: Color(0xFF353535), + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + ), + ), + ], + ), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + (memberInfor?.gainLikeTotal ?? 0).toString(), + style: TextStyle( + color: Color(0xFF353535), + fontSize: 16.sp, + fontWeight: MyFontWeight.semi_bold, + ), + ), + SizedBox( + height: 4.h, + ), + Text( + S.of(context).haoyou, + style: TextStyle( + color: Color(0xFF353535), + fontSize: 12.sp, + fontWeight: MyFontWeight.regular, + ), + ), + ], + ), + ), + ], + ), + ), + Container( + height: 1.h, + color: Color(0xFFF7F7F7), + margin: EdgeInsets.only(bottom: (memberId != selfUserId) ? 24: 0), + ), + ///关注,聊天按钮 + if (memberId != selfUserId) + Row( + children: [ + Expanded( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + vipFollow( + memberId, + (articles.isNotEmpty && + (articles.first.followed ?? false))); + }, + child: Container( + height: 41, + margin: EdgeInsets.only(right: 8.w, left: 4), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20.5), + color: (articles.isNotEmpty && + (articles.first.followed ?? false)) + ? Color(0xFFE6E6E6) + : Color(0xFF32A060), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + (articles.isNotEmpty && + (articles.first.followed ?? false)) + ? Icons.check + : Icons.add, + color: (articles.isNotEmpty && + (articles.first.followed ?? false)) + ? Color(0xFF808080) + : Colors.white, + size: 18.sp, + ), + SizedBox( + width: 5, + ), + Text( + (articles.isNotEmpty && + (articles.first.followed ?? false)) + ? S.of(context).yiguanzhu + : S.of(context).guanzhu, + style: TextStyle( + fontSize: 12.sp, + color: (articles.isNotEmpty && + (articles.first.followed ?? false)) + ? Color(0xFF808080) + : Colors.white, + fontWeight: MyFontWeight.regular, + ), + ), + ], + ), + ), + ), ), - ), - SizedBox(width: 4.w), - Image.asset( - "assets/image/vip_yk.webp", - width: 20, - height: 20, - ), - Spacer(), - if (memberId == "0") GestureDetector( + behavior: HitTestBehavior.opaque, onTap: () { - setState(() { - _toUserInfo(); - }); + if (memberInfor?.id == selfUserId) { + SmartDialog.showToast( + "不能跟自己聊天", + alignment: Alignment.center, + ); + return; + } + if (widget.arguments?["inletType"] == 1) { + //聊天框跳转到该页面inletType = 1,别的页面都是0,为了避免打开多个聊天框bug; + Navigator.of(context).pop(); + } else { + Navigator.of(context).pushNamed( + '/router/chat_details_page', + arguments: { + "toUser": ImUser( + avatar: memberInfor?.headimg, + mid: memberInfor?.id, + nickname: memberInfor?.nickname, + ), + }, + ); + } }, child: Container( - height: 23.h, - padding: EdgeInsets.only( - left: 6.w, right: 6.w, bottom: 2.h, top: 2.h, - ), + width: 110.w, + height: 41, + margin: EdgeInsets.only(right: 1.w), alignment: Alignment.center, decoration: BoxDecoration( - borderRadius: BorderRadius.circular(100), - border: Border.all( - width: 1.w, - color: Color(0xFF353535), - style: BorderStyle.solid, - ), + borderRadius: BorderRadius.circular(20.5), + color: Color(0xFFFF9640), ), child: Text( - S.of(context).bianjigerenziliao, + "聊一聊", style: TextStyle( - fontSize: 12.sp, + fontSize: 13.sp, + color: Colors.white, fontWeight: MyFontWeight.regular, - color: Color(0xFF353535), ), ), ), - ) - ], - ), - ), + ), + ], + ), + ], + ), ); } + ///动态 Widget dynamicList() { return Container( child: (articles.length == 0) @@ -708,12 +1079,15 @@ class _PersonalPage extends State with WidgetsBindingObserver { text: "目前暂无发布动态,要把开心的事讲出来哦~", fontSize: 16.sp, margin: EdgeInsets.only( - left: 60.w, right: 60.w, bottom:80.h, + left: 60.w, + right: 60.w, + bottom: 80.h, ), ) : ListView.builder( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, + padding: EdgeInsets.zero, itemBuilder: (context, position) { return InkWell( child: CommunityDynamic( @@ -724,6 +1098,7 @@ class _PersonalPage extends State with WidgetsBindingObserver { _onRefresh(); }); }, + isList: true, removalDynamic: () { setState(() { _onRefresh(); diff --git a/lib/mine/recharge_page.dart b/lib/mine/recharge_page.dart index ec87f99c..2296a976 100644 --- a/lib/mine/recharge_page.dart +++ b/lib/mine/recharge_page.dart @@ -15,6 +15,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/recharge_details_dialog.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -55,13 +56,11 @@ class _RechargePage extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, - token: value.getString("token"), - showLoading: false), - _onRefresh() - }); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); + _onRefresh(); fluwx.addSubscriber((event) async { print("payCallback: ${event.errCode}"); if (event.errCode == 0) { @@ -78,8 +77,7 @@ class _RechargePage extends State { ///会员权益列表 queryBenefitList() async { try { - BaseListData? baseData = - await apiService?.benefitList().catchError((onError) { + BaseListData? baseData = await apiService?.benefitList().catchError((onError) { return BaseListData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -98,13 +96,10 @@ class _RechargePage extends State { queryUserBalance() async { try { - BaseData? baseData = - await apiService?.queryInfo().catchError((onError) { - SmartDialog.showToast(AppUtils.dioErrorTypeToString(onError.type), - alignment: Alignment.center); + BaseData? baseData = await apiService?.queryInfo().catchError((onError) { refreshController.refreshFailed(); refreshController.loadFailed(); - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { userInfo = baseData?.data; @@ -118,9 +113,8 @@ class _RechargePage extends State { ///会员权益介绍/规则/说明/储值说明 queryRuleDetails() async { try { - BaseData? baseData = - await apiService?.vipBenefit().catchError((onError) { - return Future.value(null); + BaseData? baseData = await apiService?.vipBenefit().catchError((onError) { + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { vipRuleDetails = baseData!.data; @@ -133,9 +127,8 @@ class _RechargePage extends State { ///充值列表 queryRechargeActList() async { try { - BaseData? baseData = - await apiService?.rechargeActList("admin").catchError((onError) { - return Future.value(null); + BaseData? baseData = await apiService?.rechargeActList("admin").catchError((onError) { + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { rechargeActLists = baseData!.data; @@ -149,7 +142,7 @@ class _RechargePage extends State { SmartDialog.showLoading( msg: S.current.zhengzaijiazai, ); - // SharedPreferences value = await SharedPreferences.getInstance(); + queryBenefitList(); queryRuleDetails(); queryRechargeActList(); diff --git a/lib/mine/roll_center_page.dart b/lib/mine/roll_center_page.dart index 32c14343..5a1d26df 100644 --- a/lib/mine/roll_center_page.dart +++ b/lib/mine/roll_center_page.dart @@ -5,6 +5,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/coupon.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/coupon_details_dialog.dart'; import 'package:huixiang/view_widget/item_title.dart'; @@ -33,15 +34,12 @@ class _RollCenterPage extends State { @override void initState() { super.initState(); - - SharedPreferences.getInstance().then((value) => { - apiService = ApiService( - Dio(), - context: context, - token: value.getString('token'), - ), - queryCoupon(), - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + queryCoupon(); _refreshController = RefreshController(initialRefresh: false); } diff --git a/lib/mine/user_info_page.dart b/lib/mine/user_info_page.dart index 567fd871..bb8ef53f 100644 --- a/lib/mine/user_info_page.dart +++ b/lib/mine/user_info_page.dart @@ -11,6 +11,7 @@ import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/cupertino_date_picker.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -41,22 +42,20 @@ class _UserInfoPage extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - String? userStr = value.getString('user'); - if (userStr?.isNotEmpty ?? false) { - print(userStr); - user = UserInfo.fromJson(jsonDecode(userStr!)); - mobile = user?.phone ?? ""; - modifyInfo["nickname"] = user?.nickname ??""; - modifyInfo["signature"] = user?.signature ?? ""; - modifyInfo["birth"] = user?.birth ?? ""; - modifyInfo["headimg"] = user?.headimg ?? ""; - modifyInfo["sex"] = user?.sex ?? ""; - age = AppUtils.getAgeByString(user?.birth ?? ""); - refresh(); - apiService = ApiService(Dio(), context: context, token: value.getString('token')); - } - }); + String userStr = SharedInstance.instance.userJson; + if (userStr.isNotEmpty) { + print(userStr); + user = UserInfo.fromJson(jsonDecode(userStr!)); + mobile = user?.phone ?? ""; + modifyInfo["nickname"] = user?.nickname ??""; + modifyInfo["signature"] = user?.signature ?? ""; + modifyInfo["birth"] = user?.birth ?? ""; + modifyInfo["headimg"] = user?.headimg ?? ""; + modifyInfo["sex"] = user?.sex ?? ""; + age = AppUtils.getAgeByString(user?.birth ?? ""); + refresh(); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + } } String? age; @@ -486,7 +485,9 @@ class _UserInfoPage extends State { fileUpload() async { if ((filePath?.isNotEmpty ?? false) && await File(filePath!).exists()) { BaseData? baseData = await apiService?.upload(File(filePath!), 123123123, false) - .catchError((onError) {}); + .catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { UploadResult? uploadResult = baseData!.data; modifyInfo["headimg"] = uploadResult?.url; @@ -524,10 +525,11 @@ class _UserInfoPage extends State { Widget valueEnd() { return Container( - child: Icon( - Icons.keyboard_arrow_right, - size: 20.sp, - )); + child: Icon( + Icons.keyboard_arrow_right, + size: 20.sp, + ), + ); } Widget buildValue(type, value) { diff --git a/lib/mine/vip_balance_page.dart b/lib/mine/vip_balance_page.dart index 1d43693e..f89cb0b2 100644 --- a/lib/mine/vip_balance_page.dart +++ b/lib/mine/vip_balance_page.dart @@ -5,6 +5,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/user_bill.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -31,11 +32,8 @@ class _VipBalancePage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, token: value.getString('token')), - queryBillInfo(), - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryBillInfo(); _refreshController = RefreshController(initialRefresh: false); } diff --git a/lib/mine/vip_card_page.dart b/lib/mine/vip_card_page.dart index 79f39a77..b3f2b7d3 100644 --- a/lib/mine/vip_card_page.dart +++ b/lib/mine/vip_card_page.dart @@ -6,6 +6,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/vip_card.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -30,11 +31,8 @@ class _VipCardPage extends State { void initState() { super.initState(); _refreshController = RefreshController(); - - SharedPreferences.getInstance().then((value) { - apiService = ApiService(Dio(), context: context, token: value.getString("token")); - queryVipCard(); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + queryVipCard(); } List coupons = []; diff --git a/lib/mine/vip_detail_page.dart b/lib/mine/vip_detail_page.dart index 1c79dc11..e11576d6 100644 --- a/lib/mine/vip_detail_page.dart +++ b/lib/mine/vip_detail_page.dart @@ -71,13 +71,12 @@ class _VipDetailPage extends State { int current = 1; vipDetail(latitude, longitude) async { - final SharedPreferences value = await SharedPreferences.getInstance(); BaseData? baseData = await apiService?.vipDetail({ "id": widget.arguments?["id"], "latitude": "$latitude", "longitude": "$longitude", }).catchError((onError) { - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { vipCard = baseData!.data; diff --git a/lib/mine/vip_pay_code.dart b/lib/mine/vip_pay_code.dart index 4fd84da0..2db5de00 100644 --- a/lib/mine/vip_pay_code.dart +++ b/lib/mine/vip_pay_code.dart @@ -6,6 +6,7 @@ import 'package:flutter/services.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -46,16 +47,13 @@ class _VipPayCode extends State { ///查询用户信息 queryUser() async { try{ - SharedPreferences value = await SharedPreferences.getInstance(); BaseData? baseData = await apiService?.queryInfo().catchError((onError) { refreshController.refreshFailed(); - return Future.value(null); + return BaseData()..isSuccess = false; }); - if (baseData?.isSuccess ?? false) { - userInfo = baseData!.data; - SharedPreferences.getInstance().then((value) => { - value.setString('user', jsonEncode(baseData.data)), - }); + if ((baseData?.isSuccess ?? false) && baseData!.data != null) { + userInfo = baseData.data; + SharedInstance.instance.saveUser(baseData.data!); setState(() {}); refreshController.refreshCompleted(); }else{ diff --git a/lib/order/bargain_group_order.dart b/lib/order/bargain_group_order.dart index 1f1e6c1d..2ca0bc91 100644 --- a/lib/order/bargain_group_order.dart +++ b/lib/order/bargain_group_order.dart @@ -11,6 +11,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -138,18 +139,16 @@ class _ExchangeHistoryList extends State @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - String minToken = value.getString("minToken") ?? ""; - String tenant = value.getString("tenant") ?? ""; - String storeId = value.getString("storeId") ?? ""; - minService = MinApiService(Dio(), - context: context, - token: minToken, - tenant: tenant, - storeId: storeId, - showLoading: true); - queryShowMyActList(); - }); + String minToken = SharedInstance.instance.miniToken; + String tenant = SharedInstance.instance.tenant; + String storeId = SharedInstance.instance.storeId; + minService = MinApiService(Dio(), + context: context, + token: minToken, + tenant: tenant, + storeId: storeId, + showLoading: true); + queryShowMyActList(); } ///查看我的拼团、砍价、列表 diff --git a/lib/order/exchange_history_page.dart b/lib/order/exchange_history_page.dart index 1b307bf4..4437abca 100644 --- a/lib/order/exchange_history_page.dart +++ b/lib/order/exchange_history_page.dart @@ -8,6 +8,7 @@ import 'package:huixiang/data/page.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/icon_text.dart'; @@ -74,32 +75,29 @@ class _ExchangeHistoryPage extends State titleSize: 18.sp, background: Color(0xFFFFFFFF), leadingColor: Colors.black, - toolbarHeight: kToolbarHeight + MediaQuery.of(context).padding.top, + toolbarHeight: kToolbarHeight, bottom: PreferredSize( preferredSize: Size(double.infinity, 38.h), - child: Theme( - data: ThemeData( - splashColor: Colors.transparent, // 点击时的水波纹颜色设置为透明 - highlightColor: Colors.transparent, // 点击时的背景高亮颜色设置为透明 - ), - child: TabBar( - controller: tabcontroller, - indicatorWeight: 2, - indicatorColor: Color(0xFF39B54A), - indicatorSize: TabBarIndicatorSize.label, - indicatorPadding: EdgeInsets.only(top: 3), - unselectedLabelStyle: TextStyle( - fontSize: 16.sp, - fontWeight: FontWeight.normal, - ), - labelStyle: TextStyle( - color: Colors.black, - fontSize: 16.sp, - fontWeight: MyFontWeight.semi_bold, - ), - labelColor: Colors.black, - tabs: tabs, - )), + child: TabBar( + controller: tabcontroller, + indicatorWeight: 2, + indicatorColor: Color(0xFF39B54A), + indicatorSize: TabBarIndicatorSize.label, + indicatorPadding: EdgeInsets.only(top: 3), + unselectedLabelStyle: TextStyle( + fontSize: 16.sp, + fontWeight: FontWeight.normal, + ), + dividerHeight: 0, + dividerColor: Colors.transparent, + labelStyle: TextStyle( + color: Colors.black, + fontSize: 16.sp, + fontWeight: MyFontWeight.semi_bold, + ), + labelColor: Colors.black, + tabs: tabs, + ), ), ), body: TabBarView( @@ -134,13 +132,13 @@ class _ExchangeHistoryList extends State @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - showLoading: false, - context: context, - token: value.getString('token')), - queryHistory(), - }); + apiService = ApiService( + Dio(), + showLoading: false, + context: context, + token: SharedInstance.instance.token, + ); + queryHistory(); } queryHistory({bool isLoading = true}) async { @@ -162,6 +160,7 @@ class _ExchangeHistoryList extends State networkStatus = -1; _refreshController.loadFailed(); _refreshController.refreshFailed(); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (baseData!.data!.list?.isNotEmpty ?? false) { @@ -196,6 +195,7 @@ class _ExchangeHistoryList extends State @override Widget build(BuildContext context) { + super.build(context); return SmartRefresher( enablePullDown: true, enablePullUp: true, @@ -259,23 +259,21 @@ class _ExchangeHistoryList extends State Widget buildOrder(ExchangeOrder exchangeOrder) { return Container( margin: EdgeInsets.fromLTRB( - 16.w, - 8.h, - 16.w, - 8.h, + 12, 8, 12, 8, ), - padding: EdgeInsets.all(12), + padding: EdgeInsets.all(16), decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(8), - boxShadow: [ - BoxShadow( - color: Colors.black.withAlpha(12), - offset: Offset(0, 3), - blurRadius: 14, - spreadRadius: 0, - ) - ]), + color: Colors.white, + borderRadius: BorderRadius.circular(8), + boxShadow: [ + BoxShadow( + color: Colors.black.withAlpha(12), + offset: Offset(0, 3), + blurRadius: 14, + spreadRadius: 0, + ), + ], + ), child: Column( children: [ Row( @@ -306,104 +304,102 @@ class _ExchangeHistoryList extends State fontWeight: MyFontWeight.semi_bold, fontSize: 14.sp, ), - ) + ), ], ), SizedBox( - height: 16.h, + height: 16, ), exchangeOrder.useTyped == 1 - ? Container( - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "自提门店" + " :", - style: TextStyle( - color: Color(0xFF353535), - fontWeight: MyFontWeight.regular, - fontSize: 12.sp, - ), - ), - SizedBox( - width: 8.w, - ), - Expanded( - child: Text( - exchangeOrder.storeName ?? "", - style: TextStyle( - color: Colors.black, - fontWeight: MyFontWeight.regular, - fontSize: 12.sp, - ), - ), - ) - ], - ), - SizedBox( - height: 8.h, - ), - Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - S.of(context).zitidizhi + " :", - style: TextStyle( - color: Color(0xFF353535), - fontWeight: MyFontWeight.regular, - fontSize: 12.sp, - ), - ), - SizedBox( - width: 8.w, - ), - Expanded( - child: Text( - exchangeOrder.address ?? "", - style: TextStyle( - color: Colors.black, - fontWeight: MyFontWeight.regular, - fontSize: 12.sp, - ), - ), - ) - ], - ), - SizedBox( - height: 8.h, + ? Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "自提门店" + " :", + style: TextStyle( + color: Color(0xFF353535), + fontWeight: MyFontWeight.regular, + fontSize: 12.sp, + ), + ), + SizedBox( + width: 8.w, + ), + Expanded( + child: Text( + exchangeOrder.storeName ?? "", + style: TextStyle( + color: Colors.black, + fontWeight: MyFontWeight.regular, + fontSize: 12.sp, ), - Row( - children: [ - Text( - S.of(context).zitishijian + " :", - style: TextStyle( - color: Color(0xFF353535), - fontWeight: MyFontWeight.regular, - fontSize: 12.sp, - ), - ), - SizedBox( - width: 8.h, - ), - Expanded( - child: Text( - S.of(context).duihuanhouwugegongzuori, - style: TextStyle( - color: Colors.black, - fontWeight: MyFontWeight.regular, - fontSize: 12.sp, - ), - ), - ) - ], + ), + ) + ], + ), + SizedBox( + height: 8.h, + ), + Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + S.of(context).zitidizhi + " :", + style: TextStyle( + color: Color(0xFF353535), + fontWeight: MyFontWeight.regular, + fontSize: 12.sp, + ), + ), + SizedBox( + width: 8.w, + ), + Expanded( + child: Text( + exchangeOrder.address ?? "", + style: TextStyle( + color: Colors.black, + fontWeight: MyFontWeight.regular, + fontSize: 12.sp, ), - ], + ), + ) + ], + ), + SizedBox( + height: 8.h, + ), + Row( + children: [ + Text( + S.of(context).zitishijian + " :", + style: TextStyle( + color: Color(0xFF353535), + fontWeight: MyFontWeight.regular, + fontSize: 12.sp, + ), ), - ) + SizedBox( + width: 8.h, + ), + Expanded( + child: Text( + S.of(context).duihuanhouwugegongzuori, + style: TextStyle( + color: Colors.black, + fontWeight: MyFontWeight.regular, + fontSize: 12.sp, + ), + ), + ) + ], + ), + ], + ) : Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, @@ -433,7 +429,7 @@ class _ExchangeHistoryList extends State ], ), SizedBox( - height: 16.h, + height: 16, ), Row( mainAxisAlignment: MainAxisAlignment.start, @@ -448,42 +444,39 @@ class _ExchangeHistoryList extends State fit: BoxFit.cover, ), SizedBox( - width: 12.w, + width: 12, ), Expanded( - child: SizedBox( - // height: 66.h, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - exchangeOrder.creditOrderDetailList?[0].name ?? "", - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 14.sp, - fontWeight: MyFontWeight.semi_bold, - color: Color(0xFF353535), - ), - ), - SizedBox( - height: 5.h, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + exchangeOrder.creditOrderDetailList?[0].name ?? "", + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14.sp, + fontWeight: MyFontWeight.semi_bold, + color: Color(0xFF353535), ), - Text( - exchangeOrder.useTyped == 3 - ? S.of(context).feishiwuduihuanma - : (exchangeOrder - .creditOrderDetailList?[0].description ?? - ""), - maxLines: 2, - style: TextStyle( - fontSize: 10.sp, - fontWeight: MyFontWeight.regular, - color: Color(0xFF727272), - ), + ), + SizedBox( + height: 5.h, + ), + Text( + exchangeOrder.useTyped == 3 + ? S.of(context).feishiwuduihuanma + : (exchangeOrder + .creditOrderDetailList?[0].description ?? + ""), + maxLines: 2, + style: TextStyle( + fontSize: 10.sp, + fontWeight: MyFontWeight.regular, + color: Color(0xFF727272), ), - ], - ), + ), + ], ), flex: 1, ), @@ -494,23 +487,13 @@ class _ExchangeHistoryList extends State fontWeight: MyFontWeight.regular, color: Color(0xFF353535), ), - ) + ), ], ), Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ - // Text( - // S.of(context).shangpinjifen(90), - // style: TextStyle( - // fontSize: 12, - // color: Color(0xFFA0A0A0), - // ), - // ), - // SizedBox( - // width: 4, - // ), Text( exchangeOrder.amount == "0" ? "" @@ -530,7 +513,7 @@ class _ExchangeHistoryList extends State ], ), SizedBox( - height: 12.h, + height: 12, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -540,32 +523,27 @@ class _ExchangeHistoryList extends State "${S.of(context).dingdanbianhao}: ${exchangeOrder.orderCode}", leftImage: "assets/image/bianhao.webp", iconSize: 16, + space: 5, textStyle: TextStyle( fontSize: 12.sp, fontWeight: MyFontWeight.regular, color: Color(0xFF353535), ), ), + Spacer(), if (exchangeOrder.useTyped != 3) - (exchangeOrder.useTyped == 1 - ? GestureDetector( + (exchangeOrder.useTyped == 1 ? GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - // if (exchangeOrder.state == 1) { - // receive2Card(exchangeOrder.id); - // } else { - // Navigator.of(context) - // .pushNamed('/router/write_off_page', arguments: {}); - // } Navigator.of(context).pushNamed( - '/router/exchange_write_offPage', - arguments: { - "exchangeOrder": exchangeOrder.toJson(), - }); + '/router/exchange_write_offPage', + arguments: { + "exchangeOrder": exchangeOrder.toJson(), + }, + ); }, child: buildBtnStatus(exchangeOrder.state), - ) - : GestureDetector( + ) : GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { Navigator.of(context).pushNamed( @@ -579,12 +557,13 @@ class _ExchangeHistoryList extends State .creditOrderDetailList?[0].goodsNumber, "skuImg": exchangeOrder .creditOrderDetailList?[0].goodsMainImg - }); + }, + ); }, child: buildBtnStatusTow(exchangeOrder.sendStatus), )) ], - ) + ), ], ), ); diff --git a/lib/order/exchange_order_page.dart b/lib/order/exchange_order_page.dart index 3f661b5e..46402f09 100644 --- a/lib/order/exchange_order_page.dart +++ b/lib/order/exchange_order_page.dart @@ -11,6 +11,7 @@ import 'package:huixiang/data/wx_pay.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/receiving_method_dialog.dart'; @@ -45,16 +46,14 @@ class _ExchangeOrderPage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = ApiService(Dio(), context: context, token: value.getString("token")); - String? user = value.getString('user'); - if (user?.isNotEmpty ?? false) { - UserInfo userInfo = UserInfo.fromJson(jsonDecode(user!)); - points = userInfo.points; - happyBean = userInfo.happyBean; - } - queryUserBalance(); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + String user = SharedInstance.instance.userJson; + if (user.isNotEmpty) { + UserInfo userInfo = UserInfo.fromJson(jsonDecode(user)); + points = userInfo.points; + happyBean = userInfo.happyBean; + } + queryUserBalance(); fluwx.addSubscriber((event) async { print("payCallback: ${event.errCode}"); @@ -87,7 +86,9 @@ class _ExchangeOrderPage extends State { } queryUserBalance() async { - BaseData? baseData = await apiService?.queryInfo().catchError((onError) {}); + BaseData? baseData = await apiService?.queryInfo().catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { userInfo = baseData!.data; mBalance = double.tryParse("${userInfo?.money}") ?? 0; diff --git a/lib/order/exchange_order_success_page.dart b/lib/order/exchange_order_success_page.dart index 444e1f45..ce297340 100644 --- a/lib/order/exchange_order_success_page.dart +++ b/lib/order/exchange_order_success_page.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -36,16 +37,14 @@ class _ExchangeOrderSuccessPage extends State { double.parse((widget.arguments?["happyBeanPrice"] ?? "0").toString()).toInt(); UserInfo userInfo; - SharedPreferences.getInstance().then((value){ - apiService = ApiService(Dio(), context: context, token: value.getString("token")); - String? user = value.getString('user'); - if (user?.isEmpty ?? true) { - userInfo = UserInfo.fromJson(jsonDecode(user!)); - userInfo.points = "$price"; - userInfo.happyBean = "$happyBeanPrice"; - value.setString('user', jsonEncode(userInfo.toJson())); - } - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + String user = SharedInstance.instance.userJson; + if (user.isNotEmpty) { + userInfo = UserInfo.fromJson(jsonDecode(user!)); + userInfo.points = "$price"; + userInfo.happyBean = "$happyBeanPrice"; + SharedInstance.instance.saveUser(userInfo); + } setState(() {}); } @@ -83,7 +82,8 @@ class _ExchangeOrderSuccessPage extends State { style: TextStyle( color: Color(0xFF353535), fontSize: 21.sp, - fontWeight: MyFontWeight.semi_bold), + fontWeight: MyFontWeight.semi_bold, + ), ), SizedBox( height:45.h, diff --git a/lib/order/invoices_manage/add_invoices_title.dart b/lib/order/invoices_manage/add_invoices_title.dart index 85774526..eb6024eb 100644 --- a/lib/order/invoices_manage/add_invoices_title.dart +++ b/lib/order/invoices_manage/add_invoices_title.dart @@ -2,6 +2,7 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shimmer/shimmer.dart'; @@ -75,15 +76,12 @@ class _AddInvoicesTitle extends State { SmartDialog.showLoading( msg: S.current.zhengzaijiazai, ); - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - userId = value.getString('userId'); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } + userId = SharedInstance.instance.userId; + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); BaseData? baseData = await apiService?.invoiceHeader({ "bank": editBankController.text == "" ? (records?.bank ?? "") @@ -131,15 +129,12 @@ class _AddInvoicesTitle extends State { SmartDialog.showLoading( msg: S.current.zhengzaijiazai, ); - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - userId = value.getString('userId'); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } + userId = SharedInstance.instance.userId; + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); BaseData? baseData = await apiService?.invoiceHeaders({ "bank": editBankController.text == "" ? (records?.bank ?? "") @@ -165,16 +160,13 @@ class _AddInvoicesTitle extends State { "type": titleType == 0 ? "PERSONAL" : "COMPANY", //抬头类型 "userId": userId, //所属用户ID }).catchError((error) { - SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type), - alignment: Alignment.center); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { Navigator.of(context).pop(1); Future.delayed(Duration(milliseconds: 500), () { SmartDialog.showToast("编辑抬头信息成功", alignment: Alignment.center); }); - } else { - SmartDialog.showToast(baseData?.msg ?? "", alignment: Alignment.center); } } finally { SmartDialog.dismiss(); diff --git a/lib/order/invoices_manage/edit_invoices_info.dart b/lib/order/invoices_manage/edit_invoices_info.dart index c3e821a5..a3806948 100644 --- a/lib/order/invoices_manage/edit_invoices_info.dart +++ b/lib/order/invoices_manage/edit_invoices_info.dart @@ -2,6 +2,7 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shimmer/shimmer.dart'; @@ -53,16 +54,14 @@ class _EditInvoicesInfo extends State { } }); }); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService( - Dio(), - context: context, - token: value.getString('token'), - ), - setState(() { - mobile = value.getString('mobile'); - }) - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + setState(() { + mobile = SharedInstance.instance.mobile; + }); selectPrice = widget.arguments?["selectPrice"] ?? ""; ids = widget.arguments?["ids"] ?? []; } diff --git a/lib/order/invoices_manage/invoices_detail_page.dart b/lib/order/invoices_manage/invoices_detail_page.dart index 96b1265e..1b9f6663 100644 --- a/lib/order/invoices_manage/invoices_detail_page.dart +++ b/lib/order/invoices_manage/invoices_detail_page.dart @@ -9,6 +9,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:huixiang/order/invoices_manage/pdf_screen.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:path_provider/path_provider.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -47,14 +48,12 @@ class _InvoicesDetailPage extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService( - Dio(), - context: context, - token: value.getString('token'), - ), - queryInvoices("1797587255380934656"), - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + queryInvoices("1797587255380934656"); } ///离开页面记着销毁和清除 @@ -66,16 +65,12 @@ class _InvoicesDetailPage extends State { ///发票详情 queryInvoices(id) async { - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } - BaseData? baseData = - await apiService?.invoiceDetail(id).catchError((error) { + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + BaseData? baseData = await apiService?.invoiceDetail(id).catchError((error) { networkError = AppUtils.dioErrorTypeToString(error.type); networkStatus = -1; setState(() {}); @@ -95,7 +90,6 @@ class _InvoicesDetailPage extends State { } else { refreshController.refreshFailed(); refreshController.loadFailed(); - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } diff --git a/lib/order/invoices_manage/invoices_history.dart b/lib/order/invoices_manage/invoices_history.dart index 3eda10e2..0afc6ae4 100644 --- a/lib/order/invoices_manage/invoices_history.dart +++ b/lib/order/invoices_manage/invoices_history.dart @@ -2,20 +2,21 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/invoices_history_list.dart'; +import 'package:huixiang/generated/l10n.dart'; +import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/flutter_utils.dart'; +import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; +import 'package:huixiang/view_widget/classic_header.dart'; +import 'package:huixiang/view_widget/my_appbar.dart'; +import 'package:huixiang/view_widget/my_footer.dart'; +import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shimmer/shimmer.dart'; -import '../../data/base_data.dart'; -import '../../generated/l10n.dart'; -import '../../retrofit/retrofit_api.dart'; -import '../../utils/flutter_utils.dart'; -import '../../utils/font_weight.dart'; -import '../../view_widget/classic_header.dart'; -import '../../view_widget/my_appbar.dart'; -import '../../view_widget/my_footer.dart'; -import '../../view_widget/no_data_view.dart'; class InvoicesHistory extends StatefulWidget { @override @@ -49,13 +50,10 @@ class _InvoicesHistory extends State { ///开票列表 queryInvoiceList() async { - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService(Dio(), - context: context, - token: value.getString("token"), - showLoading: false); - } + apiService ??= ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); BaseData? baseData = await apiService?.invoicePage({ "current": _current, "size": 10, @@ -66,6 +64,7 @@ class _InvoicesHistory extends State { setState(() {}); refreshController.refreshFailed(); refreshController.loadFailed(); + return BaseData()..isSuccess = false; }); if (!mounted) return; if (baseData?.isSuccess ?? false) { @@ -91,8 +90,6 @@ class _InvoicesHistory extends State { else refreshController.loadComplete(); networkStatus = 1; - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -176,7 +173,7 @@ class _InvoicesHistory extends State { )), ], ) - : ((records == null || records.length == 0) + : ((records.isEmpty) ? NoDataView( src: "assets/image/ding_dan.webp", isShowBtn: false, @@ -190,7 +187,8 @@ class _InvoicesHistory extends State { children: [ Padding( padding: EdgeInsets.only( - top: 16.h, bottom: 16.h, left: 17.w), + top: 16.h, bottom: 16.h, left: 17.w, + ), child: Text( _timeList.toString(), style: TextStyle( @@ -198,7 +196,8 @@ class _InvoicesHistory extends State { fontSize: 14.sp, fontWeight: MyFontWeight.regular, ), - )), + ), + ), Expanded( child: ListView.builder( itemCount: records?.length ?? 0, @@ -213,13 +212,15 @@ class _InvoicesHistory extends State { '/router/invoices_detail_page', arguments: { "id": records[position].id ?? "" - }); + }, + ); }, child: invoicesHistoryList( records[position]), ); }, - )) + ), + ), ], )), ), @@ -240,7 +241,7 @@ class _InvoicesHistory extends State { offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, - ) + ), ], borderRadius: BorderRadius.circular(8), ), @@ -259,7 +260,8 @@ class _InvoicesHistory extends State { fontSize: 14.sp, fontWeight: MyFontWeight.bold, ), - )), + ), + ), Text( invoicesStatus(records.state ?? ""), style: TextStyle( @@ -267,7 +269,7 @@ class _InvoicesHistory extends State { fontSize: 14.sp, fontWeight: MyFontWeight.regular, ), - ) + ), ], ), ), @@ -283,7 +285,8 @@ class _InvoicesHistory extends State { fontSize: 16.sp, fontWeight: MyFontWeight.medium, ), - )), + ), + ), Expanded( child: Text( "电子普票", @@ -292,7 +295,8 @@ class _InvoicesHistory extends State { fontSize: 14.sp, fontWeight: MyFontWeight.regular, ), - )), + ), + ), Text( records.reviewerTime ?? records.createTime ?? "", style: TextStyle( @@ -300,7 +304,7 @@ class _InvoicesHistory extends State { fontSize: 14.sp, fontWeight: MyFontWeight.regular, ), - ) + ), ], ) ], @@ -335,7 +339,7 @@ class _InvoicesHistory extends State { offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, - ) + ), ], borderRadius: BorderRadius.circular(8), ), @@ -435,7 +439,8 @@ class _InvoicesHistory extends State { style: TextStyle( fontSize: 14.sp, color: Color(0xFF0D0D0D), - fontWeight: MyFontWeight.bold), + fontWeight: MyFontWeight.bold, + ), ), Padding( padding: EdgeInsets.symmetric(vertical: 10.h), @@ -444,7 +449,8 @@ class _InvoicesHistory extends State { style: TextStyle( fontSize: 12.sp, color: Color(0xFF7A797F), - fontWeight: MyFontWeight.regular), + fontWeight: MyFontWeight.regular, + ), ), ), GestureDetector( @@ -457,15 +463,19 @@ class _InvoicesHistory extends State { color: Color(0xff32A060), borderRadius: BorderRadius.circular(15), ), - padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 3.h), + padding: EdgeInsets.symmetric( + horizontal: 12.w, vertical: 3.h, + ), child: Text( "重试", style: TextStyle( fontSize: 14.sp, color: Colors.white, - fontWeight: MyFontWeight.regular), - )), - ) + fontWeight: MyFontWeight.regular, + ), + ), + ), + ), ], ), ); diff --git a/lib/order/invoices_manage/invoices_manage_page.dart b/lib/order/invoices_manage/invoices_manage_page.dart index 6370964a..f7b10415 100644 --- a/lib/order/invoices_manage/invoices_manage_page.dart +++ b/lib/order/invoices_manage/invoices_manage_page.dart @@ -8,6 +8,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -49,13 +50,10 @@ class _InvoicesManagePage extends State { ///开票列表 queryInvoiceList() async { - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService(Dio(), - context: context, - token: value.getString("token"), - showLoading: false); - } + apiService ??= ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); BaseData? baseData = await apiService?.invoiceOrderList({ "current": _pageNum, "size": 10, @@ -66,6 +64,7 @@ class _InvoicesManagePage extends State { setState(() {}); refreshController.refreshFailed(); refreshController.loadFailed(); + return BaseData()..isSuccess = false; }); if (!mounted) return; if (baseData?.isSuccess ?? false) { @@ -80,8 +79,6 @@ class _InvoicesManagePage extends State { else refreshController.loadComplete(); networkStatus = 1; - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -126,7 +123,8 @@ class _InvoicesManagePage extends State { '/router/invoices_title_info', arguments: { "enterType": 1, - }); + }, + ); }, child: Column( children: [ @@ -146,10 +144,11 @@ class _InvoicesManagePage extends State { fontWeight: FontWeight.bold, ), ), - ) + ), ], ), - )), + ), + ), Expanded( child: GestureDetector( behavior: HitTestBehavior.translucent, @@ -175,14 +174,18 @@ class _InvoicesManagePage extends State { fontWeight: FontWeight.bold, ), ), - ) + ), ], - ))), + ), + ), + ), ], ), ), Padding( - padding: EdgeInsets.only(left: 14.w, bottom: 6.h), + padding: EdgeInsets.only( + left: 14.w, bottom: 6.h, + ), child: Text( "可开票订单", style: TextStyle( @@ -231,7 +234,7 @@ class _InvoicesManagePage extends State { ); }, ) - : ((records == null || records.length == 0) + : ((records.isEmpty) ? NoDataView( src: "assets/image/ding_dan.webp", isShowBtn: false, @@ -241,7 +244,7 @@ class _InvoicesManagePage extends State { top: 120, left: 20, right: 20), ) : ListView.builder( - itemCount: records?.length ?? 0, + itemCount: records.length, physics: BouncingScrollPhysics(), shrinkWrap: true, itemBuilder: (context, position) { @@ -253,22 +256,23 @@ class _InvoicesManagePage extends State { !records[position].isSelect; }); }, - child: - invoicesOrderItem(records[position]), + child: invoicesOrderItem(records[position]), ); }, )), ), ), - )), - if (records != null && records.length > 0) + ), + ), + if (records.isEmpty) Container( decoration: BoxDecoration( color: Colors.white, ), width: double.infinity, padding: EdgeInsets.only( - top: 16.h, bottom: 45.h, left: 14.w, right: 17.w), + top: 16.h, bottom: 45.h, left: 14.w, right: 17.w, + ), child: Column( children: [ Padding( @@ -295,7 +299,8 @@ class _InvoicesManagePage extends State { fontSize: 20.sp, fontWeight: MyFontWeight.medium, ), - )), + ), + ), Text( "开票金额以实际发票为准", style: TextStyle( @@ -305,7 +310,8 @@ class _InvoicesManagePage extends State { ), ), ], - )), + ), + ), Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ @@ -325,7 +331,8 @@ class _InvoicesManagePage extends State { : "assets/image/icon_radio_unselected.webp", width: 16.w, height: 16.h, - )), + ), + ), ), Expanded( child: GestureDetector( @@ -344,7 +351,8 @@ class _InvoicesManagePage extends State { fontWeight: MyFontWeight.regular, ), ), - )), + ), + ), GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { @@ -386,7 +394,8 @@ class _InvoicesManagePage extends State { ), alignment: Alignment.center, padding: EdgeInsets.symmetric( - horizontal: 23.w, vertical: 8.h), + horizontal: 23.w, vertical: 8.h, + ), child: Text( "去开票", style: TextStyle( @@ -396,12 +405,12 @@ class _InvoicesManagePage extends State { ), ), ), - ) + ), ], ), ], ), - ) + ), ], ), ); @@ -437,14 +446,14 @@ class _InvoicesManagePage extends State { offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, - ) + ), ], borderRadius: BorderRadius.circular(8), ), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ - ((double.tryParse(records?.payedPrice ?? "0") ?? 0) > 0) + ((double.tryParse(records.payedPrice ?? "0") ?? 0) > 0) ? GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { @@ -454,10 +463,11 @@ class _InvoicesManagePage extends State { }, child: Container( padding: EdgeInsets.only( - right: 15.w, left: 12.w, top: 5.h, bottom: 5.h), + right: 15.w, left: 12.w, top: 5.h, bottom: 5.h, + ), alignment: Alignment.center, child: Image.asset( - (records?.isSelect ?? false) + (records.isSelect ?? false) ? "assets/image/icon_radio_selected.webp" : "assets/image/icon_radio_unselected.webp", width: 15.w, @@ -467,19 +477,21 @@ class _InvoicesManagePage extends State { ) : Container( padding: EdgeInsets.only( - right: 15.w, left: 12.w, top: 5.h, bottom: 5.h), + right: 15.w, left: 12.w, top: 5.h, bottom: 5.h, + ), alignment: Alignment.center, child: Image.asset( "assets/image/disenable_seletor_tow.webp", width: 15.w, height: 15.h, - )), + ), + ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - records?.storeName ?? "", + records.storeName ?? "", maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle( @@ -491,15 +503,16 @@ class _InvoicesManagePage extends State { Padding( padding: EdgeInsets.only(top: 8.h, bottom: 14.h), child: Text( - "订单编号:${records?.id ?? ""}", + "订单编号:${records.id ?? ""}", style: TextStyle( fontSize: 12.sp, fontWeight: MyFontWeight.medium, color: Color(0xFF353535), ), - )), + ), + ), Text( - "下单时间: ${records?.createTime ?? ""}", + "下单时间: ${records.createTime ?? ""}", style: TextStyle( fontSize: 10.sp, fontWeight: MyFontWeight.regular, @@ -507,12 +520,13 @@ class _InvoicesManagePage extends State { ), ), ], - )), + ), + ), Text.rich( TextSpan( children: [ TextSpan( - text: records?.finalPayPrice ?? "0.00", + text: records.finalPayPrice ?? "0.00", style: TextStyle( color: Color(0xFF000000), fontSize: 16.sp, @@ -547,7 +561,7 @@ class _InvoicesManagePage extends State { offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, - ) + ), ], borderRadius: BorderRadius.circular(8), ), @@ -606,9 +620,10 @@ class _InvoicesManagePage extends State { width: 170, height: 14, ), - ) + ), ], - )), + ), + ), Shimmer.fromColors( baseColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8), @@ -663,7 +678,9 @@ class _InvoicesManagePage extends State { color: Color(0xff32A060), borderRadius: BorderRadius.circular(15), ), - padding: EdgeInsets.symmetric(horizontal: 12, vertical: 3), + padding: EdgeInsets.symmetric( + horizontal: 12, vertical: 3, + ), child: Text( "重试", style: TextStyle( diff --git a/lib/order/invoices_manage/invoices_title_info.dart b/lib/order/invoices_manage/invoices_title_info.dart index dd3734f6..ba748520 100644 --- a/lib/order/invoices_manage/invoices_title_info.dart +++ b/lib/order/invoices_manage/invoices_title_info.dart @@ -2,6 +2,7 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shimmer/shimmer.dart'; @@ -65,14 +66,11 @@ class _InvoicesTitleInfo extends State { ///查询抬头信心列表 queryInvoiceHeadersList() async { - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); BaseData? baseData = await apiService?.invoiceHeaderList({ "current": _current, "map": {}, @@ -86,6 +84,7 @@ class _InvoicesTitleInfo extends State { setState(() {}); refreshController.refreshFailed(); refreshController.loadFailed(); + return BaseData()..isSuccess = false; }); if (!mounted) return; if (baseData?.isSuccess ?? false) { @@ -96,8 +95,6 @@ class _InvoicesTitleInfo extends State { else refreshController.loadComplete(); networkStatus = 1; - } else { - SmartDialog.showToast(baseData?.msg ?? "", alignment: Alignment.center); } } @@ -107,21 +104,18 @@ class _InvoicesTitleInfo extends State { SmartDialog.showLoading( msg: S.current.zhengzaijiazai, ); - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } - BaseData? baseData = - await apiService?.delInvoiceHeader(ids).catchError((error) { + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + BaseData? baseData = await apiService?.delInvoiceHeader(ids).catchError((error) { networkError = AppUtils.dioErrorTypeToString(error.type); networkStatus = -1; setState(() {}); refreshController.refreshFailed(); refreshController.loadFailed(); + return BaseData() ..isSuccess = false; }); if (baseData?.isSuccess ?? false) { await editOnRefresh(); @@ -196,7 +190,7 @@ class _InvoicesTitleInfo extends State { ); }, ) - : ((records == null || records.length == 0) + : ((records.isEmpty) ? NoDataView( src: "assets/image/guan_zhu.webp", isShowBtn: false, @@ -205,38 +199,38 @@ class _InvoicesTitleInfo extends State { margin: EdgeInsets.only(top: 120), ) : ListView.builder( - itemCount: records?.length ?? 0, + itemCount: records.length, physics: BouncingScrollPhysics(), shrinkWrap: true, itemBuilder: (context, position) { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - if (widget.arguments?["enterType"] == - 0) { + if (widget.arguments?["enterType"] == 0) { Navigator.of(context).pop({ "id": records[position].id ?? "", - "phone": records[position] - .companyPhone ?? - "", - "name": - records[position].name ?? "" + "phone": records[position].companyPhone ?? "", + "name": records[position].name ?? "" }); } }, child: titleInfoList(records[position]), ); }, - ))), + )), + ), ), - )), + ), + ), if (networkStatus == 1) GestureDetector( onTap: () { - Navigator.of(context) - .pushNamed('/router/add_invoices_title', arguments: { - "titleName": "添加抬头", - }).then((value) { + Navigator.of(context).pushNamed( + '/router/add_invoices_title', + arguments: { + "titleName": "添加抬头", + }, + ).then((value) { _current = 1; records.clear(); _onRefresh(isShowLoad: false); @@ -245,7 +239,8 @@ class _InvoicesTitleInfo extends State { child: Container( padding: EdgeInsets.symmetric(vertical: 16.h), margin: EdgeInsets.only( - bottom: 25.h, left: 20.w, right: 20.w), + bottom: 25.h, left: 20.w, right: 20.w, + ), decoration: BoxDecoration( color: Color(0xff32A060), borderRadius: BorderRadius.circular(45), @@ -270,10 +265,13 @@ class _InvoicesTitleInfo extends State { Widget titleInfoList(Records records) { return Container( padding: EdgeInsets.only( - top: ((records?.type ?? "") == "PERSONAL") ? 30.h : 14.h, - bottom: ((records?.type ?? "") == "PERSONAL") ? 30.h : 14.h, - left: 12.w), - margin: EdgeInsets.only(top: 12.h, bottom: 4.h, right: 14.w, left: 14.w), + top: ((records.type ?? "") == "PERSONAL") ? 30.h : 14.h, + bottom: ((records.type ?? "") == "PERSONAL") ? 30.h : 14.h, + left: 12.w, + ), + margin: EdgeInsets.only( + top: 12.h, bottom: 4.h, right: 14.w, left: 14.w, + ), decoration: BoxDecoration( color: Colors.white, boxShadow: [ @@ -282,7 +280,7 @@ class _InvoicesTitleInfo extends State { offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, - ) + ), ], borderRadius: BorderRadius.circular(8), ), @@ -294,7 +292,7 @@ class _InvoicesTitleInfo extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ Text( - records?.name ?? "", + records.name ?? "", maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( @@ -303,28 +301,32 @@ class _InvoicesTitleInfo extends State { fontWeight: MyFontWeight.bold, ), ), - if ((records?.type ?? "") == "COMPANY") + if ((records.type ?? "") == "COMPANY") Padding( padding: EdgeInsets.only(top: 20.h), child: Text( - "税号:${records?.taxId ?? ""}", + "税号:${records.taxId ?? ""}", style: TextStyle( color: Color(0xff353535), fontSize: 14.sp, fontWeight: MyFontWeight.regular, ), - )), + ), + ), ], - )), + ), + ), GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - Navigator.of(context) - .pushNamed('/router/add_invoices_title', arguments: { - "titleName": "编辑抬头", - "titleType": records.type == "COMPANY" ? 1 : 0, - "records": records, - }).then((value) { + Navigator.of(context).pushNamed( + '/router/add_invoices_title', + arguments: { + "titleName": "编辑抬头", + "titleType": records.type == "COMPANY" ? 1 : 0, + "records": records, + }, + ).then((value) { if (value == 1) editOnRefresh(); }); }, @@ -335,11 +337,13 @@ class _InvoicesTitleInfo extends State { width: 16.h, height: 16.h, fit: BoxFit.fitWidth, - ))), + ), + ), + ), GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - showTitleInfoDialog(records?.id ?? ""); + showTitleInfoDialog(records.id ?? ""); }, child: Padding( padding: EdgeInsets.only(left: 12.w, right: 31.w), @@ -348,7 +352,8 @@ class _InvoicesTitleInfo extends State { width: 15.h, height: 16.h, fit: BoxFit.fitWidth, - )), + ), + ), ), ], ), @@ -367,7 +372,7 @@ class _InvoicesTitleInfo extends State { offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, - ) + ), ], borderRadius: BorderRadius.circular(8), ), @@ -420,7 +425,8 @@ class _InvoicesTitleInfo extends State { ], ), ], - )), + ), + ), Row( children: [ Shimmer.fromColors( @@ -468,7 +474,8 @@ class _InvoicesTitleInfo extends State { style: TextStyle( fontSize: 14.sp, color: Color(0xFF0D0D0D), - fontWeight: MyFontWeight.bold), + fontWeight: MyFontWeight.bold, + ), ), Padding( padding: EdgeInsets.symmetric(vertical: 10.h), @@ -477,7 +484,8 @@ class _InvoicesTitleInfo extends State { style: TextStyle( fontSize: 12.sp, color: Color(0xFF7A797F), - fontWeight: MyFontWeight.regular), + fontWeight: MyFontWeight.regular, + ), ), ), GestureDetector( @@ -490,15 +498,19 @@ class _InvoicesTitleInfo extends State { color: Color(0xff32A060), borderRadius: BorderRadius.circular(15), ), - padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 3.h), + padding: EdgeInsets.symmetric( + horizontal: 12.w, vertical: 3.h, + ), child: Text( "重试", style: TextStyle( fontSize: 14.sp, color: Colors.white, - fontWeight: MyFontWeight.regular), - )), - ) + fontWeight: MyFontWeight.regular, + ), + ), + ), + ), ], ), ); @@ -568,7 +580,7 @@ class _InvoicesTitleInfo extends State { flex: 1, ), ], - ) + ), ], ), ), diff --git a/lib/order/logistics_information_page.dart b/lib/order/logistics_information_page.dart index 9bb22153..d4fe275f 100644 --- a/lib/order/logistics_information_page.dart +++ b/lib/order/logistics_information_page.dart @@ -5,15 +5,17 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/logistics.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; +import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; +import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import '../view_widget/classic_header.dart'; -import '../view_widget/my_footer.dart'; + class LogisticsInformationPage extends StatefulWidget { final arguments; @@ -35,27 +37,23 @@ class _LogisticsInformationPage extends State { super.initState(); _refreshController = RefreshController(); - SharedPreferences.getInstance().then((value) { - apiService = - ApiService(Dio(), context: context, token: value.getString("token")); - if ((widget.arguments["shipperCode"] ?? "") != "" && - (widget.arguments["logisticsNum"] ?? "") != "") - getShippingTrace(widget.arguments["shipperCode"] ?? "", - widget.arguments["logisticsNum"] ?? ""); - else - queryAppShippingTrace(widget.arguments["orderId"]); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); + if ((widget.arguments["shipperCode"] ?? "") != "" && (widget.arguments["logisticsNum"] ?? "") != "") { + getShippingTrace(widget.arguments["shipperCode"] ?? "", widget.arguments["logisticsNum"] ?? ""); + } else { + queryAppShippingTrace(widget.arguments["orderId"]); + } } List logistics = []; String shipStatus = ""; getShippingTrace(String shipperCode, String logisticCode) async { - BaseData? baseData = await apiService - ?.shippingTrace(shipperCode, logisticCode) + BaseData? baseData = await apiService?.shippingTrace(shipperCode, logisticCode) .catchError((error) { _refreshController.refreshFailed(); _refreshController.loadFailed(); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { Logistics? lgs = baseData!.data; @@ -170,7 +168,7 @@ class _LogisticsInformationPage extends State { offset: Offset(0, 2), blurRadius: 14, spreadRadius: 0, - ) + ), ], ), child: Column( @@ -183,7 +181,8 @@ class _LogisticsInformationPage extends State { style: TextStyle( fontSize: 16.sp, fontWeight: FontWeight.bold, - color: Color(0xff353535)), + color: Color(0xff353535), + ), ), ), Container( @@ -228,7 +227,7 @@ class _LogisticsInformationPage extends State { offset: Offset(0, 2), blurRadius: 14, spreadRadius: 0, - ) + ), ], ), child: Column( @@ -278,8 +277,7 @@ class _LogisticsInformationPage extends State { ), ), TextSpan( - text: - widget.arguments["productNum"].toString() ?? "", + text: widget.arguments["productNum"].toString() ?? "", style: TextStyle( fontSize: 12.sp, fontWeight: FontWeight.w400, @@ -318,14 +316,16 @@ class _LogisticsInformationPage extends State { style: TextStyle( color: Color(0xff353535), fontSize: 14.sp, - fontWeight: FontWeight.w400), + fontWeight: FontWeight.w400, + ), ), Text( shipStatus, style: TextStyle( color: Color(0xFF32A060), fontSize: 14.sp, - fontWeight: FontWeight.bold), + fontWeight: FontWeight.bold, + ), ) ], ), @@ -346,7 +346,8 @@ class _LogisticsInformationPage extends State { style: TextStyle( color: Colors.black, fontSize: 14.sp, - fontWeight: FontWeight.w400), + fontWeight: FontWeight.w400, + ), ) ], ), @@ -360,21 +361,23 @@ class _LogisticsInformationPage extends State { style: TextStyle( color: Color(0xff353535), fontSize: 14.sp, - fontWeight: FontWeight.w400), + fontWeight: FontWeight.w400, + ), ), Text( widget.arguments["logisticsNum"] ?? "", style: TextStyle( color: Colors.black, fontSize: 14.sp, - fontWeight: FontWeight.w400), - ) + fontWeight: FontWeight.w400, + ), + ), ], ), ], ), ), - ) + ), ], ), ], @@ -395,7 +398,8 @@ class _LogisticsInformationPage extends State { style: TextStyle( fontSize: 14.sp, fontWeight: MyFontWeight.medium, - color: Color(0xff353535)), + color: Color(0xff353535), + ), ), SizedBox( height: 5.h, @@ -405,7 +409,8 @@ class _LogisticsInformationPage extends State { style: TextStyle( fontSize: 12.sp, fontWeight: MyFontWeight.medium, - color: Color(0xff868686)), + color: Color(0xff868686), + ), ), ], ), @@ -428,7 +433,7 @@ class _LogisticsInformationPage extends State { decoration: new BoxDecoration( color: Color(0xffE1E1E1), ), - ) + ), ], ), SizedBox( diff --git a/lib/order/order_detail_page.dart b/lib/order/order_detail_page.dart index 863f9f2a..a44b1922 100644 --- a/lib/order/order_detail_page.dart +++ b/lib/order/order_detail_page.dart @@ -14,6 +14,7 @@ import 'package:huixiang/order/order_view/order_status.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/icon_text.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; @@ -47,18 +48,14 @@ class _OrderDetailPage extends State { void initState() { super.initState(); jumpState = widget.arguments["jumpState"]; - SharedPreferences.getInstance().then((value) { - SmartDialog.showLoading( - msg: S.of(context).zhengzaijiazai, - ); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - queryDetails(); - queryUserBalance(); - }); + + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + queryDetails(); + queryUserBalance(); } /// 小程序登录 @@ -66,18 +63,12 @@ class _OrderDetailPage extends State { apiService?.minLogin(orderInfo?.storeId ?? "").catchError((onError) { debugPrint("${onError}"); }).then((baseData) { - if (baseData?.isSuccess ?? false) { + if (baseData.isSuccess ?? false) { Map minStoreInfo = baseData.data; String minToken = minStoreInfo["token"]; String tenant = orderInfo?.tenantCode ?? ""; String storeId = orderInfo?.storeId ?? ""; - SharedPreferences.getInstance().then( - (value) => { - value.setString('minToken', minToken), - value.setString('tenant', tenant), - value.setString('storeId', storeId), - }, - ); + SharedInstance.instance.saveMini(minToken, tenant, storeId); minService = MinApiService( Dio(), // showLoading:true, @@ -92,13 +83,13 @@ class _OrderDetailPage extends State { ///查询用户信息 queryUserBalance() async { - BaseData? baseData = - await apiService?.queryInfo().catchError((onError) {}); + BaseData? baseData = await apiService?.queryInfo() + .catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { userInfo = baseData!.data; if (mounted) setState(() {}); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -110,12 +101,14 @@ class _OrderDetailPage extends State { int refundStatus = 0; queryDetails() async { + SmartDialog.showLoading( + msg: S.current.zhengzaijiazai, + ); BaseData? baseData = await apiService?.orderDetail(widget.arguments["id"]) .catchError((error) { - SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type), - alignment: Alignment.center); refreshController.refreshFailed(); refreshController.loadFailed(); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { orderInfo = baseData?.data; @@ -141,7 +134,6 @@ class _OrderDetailPage extends State { refreshController.loadComplete(); } else { SmartDialog.dismiss(); - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); refreshController.refreshFailed(); refreshController.loadFailed(); } @@ -154,12 +146,6 @@ class _OrderDetailPage extends State { child: Stack( children: [ Container( - // height: (orderStatus >= 4 ? 118.h : 118.h) + - // MediaQuery.of(context).padding.top + - // kToolbarHeight + - // 48.h, - // color: Color(0xFF3A405A), - // width: MediaQuery.of(context).size.width, decoration: BoxDecoration( image: DecorationImage( fit: BoxFit.fill, @@ -200,19 +186,21 @@ class _OrderDetailPage extends State { child: Column( children: [ ///订单状态显示 - OrderStatus( - orderStatus, - isTakeOut, - sendStatus, - payStatus, - refundStatus, - title, - center, - orderInfo, - ), + if (orderInfo != null) + OrderStatus( + orderStatus, + isTakeOut, + sendStatus, + payStatus, + refundStatus, + title, + center, + orderInfo, + ), ///订单取货地址,或, 收货地址 - OrderAddress( + if (orderInfo != null) + OrderAddress( orderStatus, isTakeOut, sendStatus, @@ -227,10 +215,12 @@ class _OrderDetailPage extends State { jumpState ?? 0), ///订单商品 - OrderCommodity(orderInfo), + if (orderInfo != null) + OrderCommodity(orderInfo), ///显示订单信息 - OrderInfoView(orderInfo, isTakeOut), + if (orderInfo != null) + OrderInfoView(orderInfo, isTakeOut), Container( height: 42.h, ), @@ -238,7 +228,7 @@ class _OrderDetailPage extends State { ), ), ), - ) + ), ], ), ); diff --git a/lib/order/order_history_page.dart b/lib/order/order_history_page.dart index 5d4f7ff3..44c4c8f9 100644 --- a/lib/order/order_history_page.dart +++ b/lib/order/order_history_page.dart @@ -14,6 +14,7 @@ import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/store/scan.dart'; import 'package:huixiang/utils/app_util.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/utils/status_utils.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; @@ -24,7 +25,7 @@ import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:huixiang/view_widget/tips_dialog.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:retrofit/retrofit.dart'; -import 'package:shared_preferences/shared_preferences.dart'; + import 'package:shimmer/shimmer.dart'; class OrderHistoryPage extends StatefulWidget { @@ -143,17 +144,16 @@ class _OrderHistoryList extends State @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService( - Dio(), - // showLoading: true, - context: context, - token: value.getString("token"), - errorLogger: this, - ), - queryOrder(), - queryUserBalance(), - }); + + apiService = ApiService( + Dio(), + // showLoading: true, + context: context, + token: SharedInstance.instance.token, + errorLogger: this, + ); + queryOrder(); + queryUserBalance(); } _onRefresh() { @@ -187,10 +187,7 @@ class _OrderHistoryList extends State } orderInfos.addAll(baseData.data!.records!); } - // baseData.data.records.forEach((element) { - // if(element.orderType==0||(element.orderType==1 && element.payStatus==1 && element.refundStatus == 0)||(element.orderType==2 && element.payStatus==1&& element.refundStatus == 0)||(element.orderType==3 && element.payStatus==1&& element.refundStatus == 0)) - // orderInfos.add(element); - // }); + refreshController.refreshCompleted(); refreshController.loadComplete(); if (current * 10 > (int.tryParse("${baseData.data?.total}") ?? 0)) { @@ -223,13 +220,8 @@ class _OrderHistoryList extends State String minToken = minStoreInfo["token"]; String tenant = orderInfo.tenantCode ?? ""; String storeId = orderInfo.storeId ?? ""; - SharedPreferences.getInstance().then( - (value) => { - value.setString('minToken', minToken), - value.setString('tenant', tenant), - value.setString('storeId', storeId), - }, - ); + SharedInstance.instance.saveMini(minToken, tenant, storeId); + paySelected( orderInfo, MinApiService( @@ -246,8 +238,7 @@ class _OrderHistoryList extends State } queryDetails(id) async { - BaseData? baseData = - await apiService?.orderDetail(id).catchError((error) { + BaseData? baseData = await apiService?.orderDetail(id).catchError((error) { return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -256,15 +247,12 @@ class _OrderHistoryList extends State } queryUserBalance() async { - BaseData? baseData = - await apiService?.queryInfo().catchError((onError) { + BaseData? baseData = await apiService?.queryInfo().catchError((onError) { return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { userInfo = baseData!.data; if (mounted) setState(() {}); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -301,15 +289,12 @@ class _OrderHistoryList extends State payResult(BaseData baseData) {} orderCancel(String orderId) async { - BaseData? baseData = - await apiService?.orderCancel(orderId).catchError((onError) { + BaseData? baseData = await apiService?.orderCancel(orderId).catchError((onError) { return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { SmartDialog.showToast("订单取消成功"); _onRefresh(); - } else { - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); } } @@ -368,6 +353,9 @@ class _OrderHistoryList extends State : ((orderInfos.length > 0) ? ListView.builder( itemCount: orderInfos.length ?? 0, + padding: EdgeInsets.symmetric( + vertical: 8, + ), itemBuilder: (context, position) { return InkWell( onTap: () { @@ -404,10 +392,7 @@ class _OrderHistoryList extends State Widget orderItem(OrderInfo orderInfo) { return Container( margin: EdgeInsets.fromLTRB( - 16.w, - 8.h, - 16.w, - 8.h, + 12, 8, 12, 8, ), decoration: BoxDecoration( color: Colors.white, @@ -429,56 +414,6 @@ class _OrderHistoryList extends State mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ - // (orderInfo != null && orderInfo.orderType == 0) - // ? Container() - // : Container( - // width: 19, - // height: 21, - // margin: EdgeInsets.only(left: 12.w, top: 12.h), - // alignment: Alignment.center, - // decoration: BoxDecoration( - // color: Colors.white, - // borderRadius: BorderRadius.circular(2), - // border: Border.all( - // width: 1, - // color: Color(0xFF32A060), - // style: BorderStyle.solid, - // )), - // child: Text( - // (orderInfo != null && orderInfo.orderType == 1) - // ? "团" - // : ((orderInfo != null && orderInfo.orderType == 2) - // ? "秒" - // : "砍"), - // style: TextStyle( - // fontSize: 12.sp, - // fontWeight: FontWeight.bold, - // color: Color(0xFF32A060), - // ), - // ), - // ), - // Container( - // width: 19, - // height: 21, - // margin: EdgeInsets.only(left: 7.w, top: 12.h), - // alignment: Alignment.center, - // decoration: BoxDecoration( - // color: Color(0xff32A060), - // borderRadius: BorderRadius.circular(2), - // ), - // child: Text( - // (orderInfo != null && orderInfo.isTakeOut == 0) - // ? "自" - // : ((orderInfo != null && orderInfo.isTakeOut == 1) - // ? "外" - // : "物"), - // style: TextStyle( - // fontSize: 12.sp, - // fontWeight: FontWeight.bold, - // color: Colors.white, - // ), - // ), - // ), Expanded( child: Container( width: double.infinity, @@ -510,9 +445,7 @@ class _OrderHistoryList extends State style: TextStyle( fontSize: 14.sp, fontWeight: FontWeight.bold, - color: (orderInfo == null) - ? Color(0xFF32A060) - : (orderInfo.refundStatus == 1 || + color: (orderInfo.refundStatus == 1 || orderInfo.orderStatus == -1 || (orderInfo.orderStatus ?? 0) >= 5) ? Colors.grey @@ -641,49 +574,47 @@ class _OrderHistoryList extends State ], ), SizedBox( - height: 8.h, + height: 8, ), Row( - children: (orderInfo != null) - ? StatusUtils.statusBtn( - context, - orderInfo.payStatus, - orderInfo.payChannel, - orderInfo.orderStatus, - orderInfo.isTakeOut, - orderInfo.sendStatus, - orderInfo.refundStatus, - orderInfo.dayFlowCode, (type) { - if (type == 0) { - aginOrder(orderInfo); - } else if (type == 1) { - SmartDialog.show( - builder: (ctx) => Tips( - () { - SmartDialog.dismiss(); - }, - text: "暂不支持此功能", - )); - } else if (type == 2) { - orderCancel(orderInfo.id ?? ""); - } else if (type == 3) { - minLogin(orderInfo); - } else if (type == 4) { - Navigator.of(context).pushNamed( - '/router/logistics_information_page', - arguments: { - "logisticsNum": orderInfo.logisticsNum, - "logisticsName": orderInfo.logisticsName, - "shipperCode": orderInfo.shipperCode, - "productNum": - orderInfo.productList?.length ?? 0, - "skuImg": - orderInfo.productList?[0].skuImg ?? "" - }, - ); - } - }) - : [], + children: StatusUtils.statusBtn( + context, + orderInfo.payStatus, + orderInfo.payChannel, + orderInfo.orderStatus, + orderInfo.isTakeOut, + orderInfo.sendStatus, + orderInfo.refundStatus, + orderInfo.dayFlowCode, (type) { + if (type == 0) { + aginOrder(orderInfo); + } else if (type == 1) { + SmartDialog.show( + builder: (ctx) => Tips( + () { + SmartDialog.dismiss(); + }, + text: "暂不支持此功能", + )); + } else if (type == 2) { + orderCancel(orderInfo.id ?? ""); + } else if (type == 3) { + minLogin(orderInfo); + } else if (type == 4) { + Navigator.of(context).pushNamed( + '/router/logistics_information_page', + arguments: { + "logisticsNum": orderInfo.logisticsNum, + "logisticsName": orderInfo.logisticsName, + "shipperCode": orderInfo.shipperCode, + "productNum": + orderInfo.productList?.length ?? 0, + "skuImg": + orderInfo.productList?[0].skuImg ?? "" + }, + ); + } + }), ), ], ), diff --git a/lib/order/order_view/order_address.dart b/lib/order/order_view/order_address.dart index d81e30b1..46a2f9ad 100644 --- a/lib/order/order_view/order_address.dart +++ b/lib/order/order_view/order_address.dart @@ -50,7 +50,7 @@ class _OrderAddress extends State { @override Widget build(BuildContext context) { return Container( - margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 20.h, bottom: 2.h), + margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 18, bottom: 2.h), padding: EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.white, @@ -89,7 +89,8 @@ class _OrderAddress extends State { style: TextStyle( fontSize: 15.sp, color: Color(0xFF4C4C4C), - fontWeight: MyFontWeight.medium), + fontWeight: MyFontWeight.medium, + ), ), SizedBox( width: 7.w, @@ -101,7 +102,8 @@ class _OrderAddress extends State { style: TextStyle( fontSize: 15.sp, color: Color(0xFF4C4C4C), - fontWeight: MyFontWeight.medium), + fontWeight: MyFontWeight.medium, + ), ), ), ], @@ -122,7 +124,9 @@ class _OrderAddress extends State { Visibility( visible: widget.orderStatus < 5 && widget.refundStatus == 0, child: Container( - margin: EdgeInsets.only(top: 20.h, bottom: 16.h), + margin: EdgeInsets.only( + top: 20.h, bottom: 16.h, + ), child: MySeparator( width: 5.w, height: 1.h, @@ -198,8 +202,7 @@ class _OrderAddress extends State { widget.carryOnPay(); } else { String storeId = widget.orderInfo?.storeVO?.id ?? ""; - String storeName = - widget.orderInfo?.storeVO?.storeName ?? ""; + String storeName = widget.orderInfo?.storeVO?.storeName ?? ""; aginOrder(storeId, storeName); } }, diff --git a/lib/order/order_view/order_commodity.dart b/lib/order/order_view/order_commodity.dart index e3e90692..04ffaf26 100644 --- a/lib/order/order_view/order_commodity.dart +++ b/lib/order/order_view/order_commodity.dart @@ -68,7 +68,6 @@ class _OrderCommodity extends State { List commodityList() { List widgets = []; widgets.addAll(widget.orderInfo?.productList?.map((e) => commodityItem(e)).toList() ?? []); - widgets.add(SizedBox(height: 20.h)); if (widget.orderInfo?.isTakeOut != 0 && widget.orderInfo?.isTakeOut != 3 && widget.orderInfo?.isTakeOut != 4) { // 配送费 @@ -107,17 +106,17 @@ class _OrderCommodity extends State { ); } - // 优惠券 - if((widget.orderInfo?.orderDetail?.couponDTO?.money ??"0") != "0") - widgets.add( - discountItem( - Color(0xFFFF7A1A), - S.of(context).youhuiquan, - widget.orderInfo?.orderDetail?.couponDTO?.name ??"", - widget.orderInfo?.orderDetail?.couponDTO?.money ??"0", - ), - ); + if ((widget.orderInfo?.orderDetail?.couponDTO?.money ??"0") != "0") { + widgets.add( + discountItem( + Color(0xFFFF7A1A), + S.of(context).youhuiquan, + widget.orderInfo?.orderDetail?.couponDTO?.name ??"", + widget.orderInfo?.orderDetail?.couponDTO?.money ??"0", + ), + ); + } if ((double.tryParse("${widget.orderInfo?.orderDetail?.activityPrice}") ?? 0) > 0) { // 活动 @@ -151,10 +150,11 @@ class _OrderCommodity extends State { // orderInfo.storeVO.couponVO.f)); // Color(0xFFFF7A1A) } + widgets.add(Container( margin: EdgeInsets.only( - top: 24.h, - bottom: 4.h, + top: 18, + bottom: 6, ), child: MySeparator( height: 1, @@ -168,11 +168,13 @@ class _OrderCommodity extends State { Widget commodityItem(OrderProductVO productList) { - return Container( - margin: EdgeInsets.only(top: 8.h, bottom: 8.h), - child: Column( - children: [ - Row( + return Column( + children: [ + Container( + margin: EdgeInsets.symmetric( + vertical: 8, + ), + child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ MImage( @@ -190,7 +192,6 @@ class _OrderCommodity extends State { margin: EdgeInsets.only( left: 8.w, ), - // height: 44.h, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, @@ -205,17 +206,15 @@ class _OrderCommodity extends State { color: Color(0xFF353535), ), ), - SizedBox( - height: 4.h, - ), - Text( - "${productList.skuNameStr ?? ""}", - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 10.sp, - color: Color(0xFFA29E9E), + if (productList.skuNameStr?.isNotEmpty ?? false) + Text( + productList.skuNameStr ?? "", + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10.sp, + color: Color(0xFFA29E9E), + ), ), - ), Text( "x${productList.buyNum}", style: TextStyle( @@ -256,19 +255,19 @@ class _OrderCommodity extends State { ), ], ), - if (productList.setMealDataList?.isNotEmpty ?? false) - ListView.builder( - itemCount: productList.setMealDataList?.length ?? 0, - scrollDirection: Axis.vertical, - physics: BouncingScrollPhysics(), - shrinkWrap: true, - padding: EdgeInsets.zero, - itemBuilder: (context, index) { - return orderMealsItem(productList.setMealDataList![index]); - }, - ), - ], - ), + ), + if (productList.setMealDataList?.isNotEmpty ?? false) + ListView.builder( + itemCount: productList.setMealDataList?.length ?? 0, + scrollDirection: Axis.vertical, + physics: BouncingScrollPhysics(), + shrinkWrap: true, + padding: EdgeInsets.zero, + itemBuilder: (context, index) { + return orderMealsItem(productList.setMealDataList![index]); + }, + ), + ], ); } diff --git a/lib/order/order_view/order_status.dart b/lib/order/order_view/order_status.dart index 01b30a7a..f3779815 100644 --- a/lib/order/order_view/order_status.dart +++ b/lib/order/order_view/order_status.dart @@ -41,21 +41,22 @@ class _OrderStatus extends State with SingleTickerProviderStateMixi vsync: this, ); _animation = Tween(begin: 0, end: 1).animate(_controller); - _controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - Future.delayed(Duration(seconds: 1), () { - _controller.stop(); - _controller.reset(); - }); - } else if (status == AnimationStatus.dismissed) { - _controller.forward(); - } - }); + _controller.addStatusListener(_statusListener); _controller.forward(); } + _statusListener(status) { + if (status == AnimationStatus.completed) { + _controller.reset(); + } else if (status == AnimationStatus.dismissed) { + _controller.forward(); + } + } + @override void dispose() { + _controller.removeStatusListener(_statusListener); + _controller.stop(); _controller.dispose(); super.dispose(); } @@ -63,151 +64,127 @@ class _OrderStatus extends State with SingleTickerProviderStateMixi @override Widget build(BuildContext context) { return Container( - height: widget.orderStatus >= 4 ? 120.h : 120.h, - padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 10.h), - child: Column( - children: [ - // Visibility( - // visible: widget.center != null && widget.center != "", - // child: Container( - // child: IconText( - // (widget.center != null && widget.center != "") ? widget.center : "", - // // leftImage: "assets/image/icon_order_ok.webp", - // // iconSize: 40.w, - // textStyle: TextStyle( - // fontSize: 18.sp, - // fontWeight: MyFontWeight.semi_bold, - // color: Colors.white, - // ), - // ), - // ), - // ), - Expanded( - child: Row( - mainAxisAlignment: MainAxisAlignment.end, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Expanded( - child: Column( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - RoundButton( - text: widget.isTakeOut == 0 - ? S.of(context).ziqu - : widget.isTakeOut == 4 ? "堂食" - :widget.isTakeOut == 3 ? "打包" - :(widget.isTakeOut == 1 - ? S.of(context).waimai - : "物流"), - width: 46.w * AppUtils.textScale(context), - height: 20.h * AppUtils.textScale(context), - textColor: Color(0xFF32A060), - fontSize: 14.sp, - padding: - EdgeInsets.symmetric(horizontal:8), - backgroup: Color(0xFFFFFFFF), - radius: 15.w, + padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 0), + constraints: BoxConstraints( + minHeight: 58.h, + ), + child: IntrinsicHeight( + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + RoundButton( + text: widget.isTakeOut == 0 + ? S.of(context).ziqu + : widget.isTakeOut == 4 ? "堂食" + :widget.isTakeOut == 3 ? "打包" + :(widget.isTakeOut == 1 + ? S.of(context).waimai + : "物流"), + width: 46.w * AppUtils.textScale(context), + height: 20.h, + textColor: Color(0xFF32A060), + fontSize: 14.sp, + padding: EdgeInsets.symmetric(horizontal: 8), + backgroup: Color(0xFFFFFFFF), + radius: 15.w, + ), + Text( + widget.title, + style: TextStyle( + color: Colors.white, + fontWeight: MyFontWeight.regular, + fontSize: 15.sp, ), - Row( - mainAxisAlignment:MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Column( - mainAxisAlignment:MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - widget.title, - style: TextStyle( - color: Colors.white, - fontWeight: MyFontWeight.regular, - fontSize: 15.sp, - ), - ), - if(widget.title == S.of(context).shangjiazhengzaipeican) - Container( - margin: EdgeInsets.only(top:5), - padding: EdgeInsets.only(top:2,left:4,right:4,bottom:2), - decoration: BoxDecoration( - color: Color(0xFF32A060), - boxShadow: [ - BoxShadow( - color: Colors.black.withAlpha(15), - offset: Offset(0, 3), - blurRadius: 14, - spreadRadius: 0, - ), - ], - borderRadius: BorderRadius.circular(15), - ), - child: Text( - S.of(context).qudanhao(": ${widget.orderInfo?.dayFlowCode}"), - style: TextStyle( - color:Colors.white, - fontFamily: 'JDZhengHT', - fontWeight: MyFontWeight.regular, - fontSize: 14.sp, - ), - ), - ), - ], + ), + if(widget.title == S.of(context).shangjiazhengzaipeican) + Container( + margin: EdgeInsets.only(top:5), + padding: EdgeInsets.only( + top: 2, left: 4, right: 4, bottom: 2, + ), + decoration: BoxDecoration( + color: Color(0xFF32A060), + boxShadow: [ + BoxShadow( + color: Colors.black.withAlpha(15), + offset: Offset(0, 3), + blurRadius: 14, + spreadRadius: 0, ), - if(widget.payStatus != 0) - (widget.title == "商家正在配餐" || widget.title == "订单待发货"|| widget.title == "商家已发货") ? - AnimatedBuilder( - animation: _animation, - builder: (BuildContext context, Widget? child) { - return Transform.rotate( - angle: _animation.value * 1 * 3.14159, - child: Image.asset( - statusPicture(widget.title), - height: 66.h, - width:66.w, - ), - alignment: Alignment.center, - ); - }, - ):Image.asset( - statusPicture(widget.title), - height: 66.h, - width:66.w, - ), ], + borderRadius: BorderRadius.circular(15), + ), + child: Text( + S.of(context).qudanhao(": ${widget.orderInfo?.dayFlowCode}"), + style: TextStyle( + color:Colors.white, + fontFamily: 'JDZhengHT', + fontWeight: MyFontWeight.regular, + fontSize: 14.sp, + ), ), - ], - ), - flex: 1, - ), - Visibility( - child: Container( - height: 33.h, - child: Row( - mainAxisSize: MainAxisSize.min, - children: timeWidget(), ), - ), - visible: (widget.orderStatus == -1 || widget.orderStatus >= 4 || widget.isTakeOut == 2) - ? false - : (widget.isTakeOut == 0) - ? !(widget.payStatus == 1) - : (widget.isTakeOut == 1) - ? !(widget.payStatus == 1 && - (widget.sendStatus != 2 && - widget.sendStatus != 3)) - : !(widget.payStatus == 1 && - (widget.sendStatus != 1)), - ), - ], + ], + ), + flex: 1, ), - flex: 1, - ), - ], + if(statusImageisShow()) + (widget.title == "商家正在配餐" || widget.title == "订单待发货"|| widget.title == "商家已发货") + ? AnimatedBuilder( + animation: _animation, + builder: (BuildContext context, Widget? child) { + return Transform.rotate( + angle: _animation.value * 1 * 3.14159, + child: Image.asset( + statusPicture(widget.title), + height: 66.h, + width:66.w, + ), + alignment: Alignment.center, + ); + }, + ) + : Image.asset( + statusPicture(widget.title), + height: 66.h, + width:66.w, + ), + if (timeIsShow()) + Container( + height: 33.h, + child: Row( + mainAxisSize: MainAxisSize.min, + children: timeWidget(), + ), + ), + ], + ), ), ); } + statusImageisShow() { + return widget.payStatus != 0; + } + + timeIsShow() { + return (widget.orderStatus == -1 || widget.orderStatus >= 4 || widget.isTakeOut == 2) + ? false + : (widget.isTakeOut == 0) + ? !(widget.payStatus == 1) + : (widget.isTakeOut == 1) + ? !(widget.payStatus == 1 && + (widget.sendStatus != 2 && + widget.sendStatus != 3)) + : !(widget.payStatus == 1 && + (widget.sendStatus != 1)); + } List timeWidget() { String hour = ""; diff --git a/lib/qr/invite_friends.dart b/lib/qr/invite_friends.dart index b22e27d0..db99b1c5 100644 --- a/lib/qr/invite_friends.dart +++ b/lib/qr/invite_friends.dart @@ -15,6 +15,7 @@ import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/constant.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/no_data_view.dart'; @@ -43,32 +44,28 @@ class _InviteFriends extends State { @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - String? user = value.getString('user'); - if (user?.isNotEmpty ?? false) { - phone = UserInfo.fromJson(jsonDecode(user!)).inviteCode; - setState(() {}); - } - if (apiService != null) - apiService = ApiService(Dio(), - context: context, - token: value.getString('token'), - showLoading: false); - queryUserInfo(); - queryInviteMember(); - }); + String? user = SharedInstance.instance.userJson; + if (user.isNotEmpty) { + phone = UserInfo.fromJson(jsonDecode(user)).inviteCode; + setState(() {}); + } + apiService ??= ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: false); + queryUserInfo(); + queryInviteMember(); } ///邀请记录 queryInviteMember() async { - BaseData>? baseData = - await apiService?.inviteMemberList({ + BaseData>? baseData = await apiService?.inviteMemberList({ "searchKey": "", "pageNum": 1, "pageSize": 100, }).catchError((error) { refreshController.refreshFailed(); - return Future.value(null); + return BaseData>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (baseData!.data != null && @@ -88,20 +85,15 @@ class _InviteFriends extends State { ///查询用户信息 queryUserInfo() async { - BaseData? baseDate = - await apiService?.queryInfo().catchError((onError) { + BaseData? baseDate = await apiService?.queryInfo().catchError((onError) { refreshController.refreshFailed(); - return Future.value(null); + return BaseData()..isSuccess = false; }); - if (baseDate?.isSuccess ?? false) { + if ((baseDate?.isSuccess ?? false) && baseDate!.data != null) { setState(() { - userInfo = baseDate!.data; + userInfo = baseDate.data; }); - SharedPreferences.getInstance().then( - (value) => { - value.setString('user', jsonEncode(baseDate!.data)), - }, - ); + SharedInstance.instance.saveUser(baseDate.data!); refreshController.refreshCompleted(); } else { refreshController.refreshFailed(); @@ -323,33 +315,33 @@ class _InviteFriends extends State { alignment: Alignment.center, width: 42.h, child: Image.asset( - "assets/image/invite_1.webp", - width: 24.h, - height: 24.h, - fit: BoxFit.cover, - ), + "assets/image/invite_1.webp", + width: 24.h, + height: 24.h, + fit: BoxFit.cover, + ), ), Spacer(), Container( alignment: Alignment.center, width: 42.h, child: Image.asset( - "assets/image/invite_2.webp", - width: 24.h, - height: 24.h, - fit: BoxFit.cover, - ), + "assets/image/invite_2.webp", + width: 24.h, + height: 24.h, + fit: BoxFit.cover, + ), ), Spacer(), Container( alignment: Alignment.center, width: 42.h, child: Image.asset( - "assets/image/invite_3.webp", - width: 24.h, - height: 24.h, - fit: BoxFit.cover, - ), + "assets/image/invite_3.webp", + width: 24.h, + height: 24.h, + fit: BoxFit.cover, + ), ), Spacer(), Container( diff --git a/lib/qr/qr_share.dart b/lib/qr/qr_share.dart index 06a5fe53..2bab09af 100644 --- a/lib/qr/qr_share.dart +++ b/lib/qr/qr_share.dart @@ -8,6 +8,7 @@ import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/qr/qr_share_image.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -25,13 +26,10 @@ class _QrSharePage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - String? user = value.getString('user'); - if (user?.isNotEmpty ?? false) { - phone = UserInfo.fromJson(jsonDecode(user!)).inviteCode; - setState(() {}); - } - }); + String user = SharedInstance.instance.userJson; + if (user.isNotEmpty) { + phone = UserInfo.fromJson(jsonDecode(user)).inviteCode; + } buildImageInfo(); } diff --git a/lib/retrofit/min_api.dart b/lib/retrofit/min_api.dart index f8dba84f..98af3c59 100644 --- a/lib/retrofit/min_api.dart +++ b/lib/retrofit/min_api.dart @@ -24,6 +24,7 @@ import 'package:huixiang/data/mini_detail.dart'; import 'package:huixiang/data/settle_order_info.dart'; import 'package:huixiang/data/shoping_home_config.dart'; import 'package:huixiang/data/shopping_cart.dart'; +import 'package:huixiang/data/store_info.dart'; import 'package:huixiang/data/wx_pay.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; @@ -219,7 +220,7 @@ abstract class MinApiService { ///查询店铺商家详情 @POST("store/getStore") - Future queryStoreInfo1(@Body() Map param); + Future> queryStoreInfo1(@Body() Map param); /// 父订单信息 @GET("order/getParentInfo?tableId={tableId}") diff --git a/lib/retrofit/min_api.g.dart b/lib/retrofit/min_api.g.dart index b8be6150..1353de1c 100644 --- a/lib/retrofit/min_api.g.dart +++ b/lib/retrofit/min_api.g.dart @@ -580,13 +580,14 @@ class _MinApiService implements MinApiService { } @override - Future> queryStoreInfo1(Map param) async { + Future> queryStoreInfo1( + Map param) async { final _extra = {}; final queryParameters = {}; final _headers = {}; final _data = {}; _data.addAll(param); - final _options = _setStreamType>(Options( + final _options = _setStreamType>(Options( method: 'POST', headers: _headers, extra: _extra, @@ -603,11 +604,11 @@ class _MinApiService implements MinApiService { baseUrl, ))); final _result = await _dio.fetch>(_options); - late BaseData _value; + late BaseData _value; try { - _value = BaseData.fromJson( + _value = BaseData.fromJson( _result.data!, - (json) => json as dynamic, + (json) => StoreInfo.fromJson(json as Map), ); } on Object catch (e, s) { errorLogger?.logError(e, s, _options); diff --git a/lib/retrofit/retrofit_api.dart b/lib/retrofit/retrofit_api.dart index e3afb017..1f7a1503 100644 --- a/lib/retrofit/retrofit_api.dart +++ b/lib/retrofit/retrofit_api.dart @@ -114,8 +114,7 @@ abstract class ApiService { debugPrint("headers = ${options.headers}"); if (context != null && showLoading && - !SmartDialog.checkExist( - dialogTypes: {SmartAllDialogType.loading})) { + !SmartDialog.checkExist(dialogTypes: {SmartAllDialogType.loading})) { //是否显示loading SmartDialog.showLoading( msg: S.of(context).zhengzaijiazai, @@ -240,7 +239,7 @@ abstract class ApiService { ///查询用户信息 @GET("/member/info") - Future> queryInfo(); + Future?> queryInfo(); ///编辑用户信息 @POST("/member/editMemberInfo") diff --git a/lib/retrofit/retrofit_api.g.dart b/lib/retrofit/retrofit_api.g.dart index 78a74195..3891a9f3 100644 --- a/lib/retrofit/retrofit_api.g.dart +++ b/lib/retrofit/retrofit_api.g.dart @@ -14,7 +14,7 @@ class _ApiService implements ApiService { this.baseUrl, this.errorLogger, }) { - baseUrl ??= 'https://pos.platform.yixinhuixiang.com/app/'; + baseUrl ??= 'http://192.168.10.54:8766/app/'; } final Dio _dio; @@ -369,7 +369,7 @@ class _ApiService implements ApiService { } @override - Future> queryInfo() async { + Future?> queryInfo() async { final _extra = {}; final queryParameters = {}; final _headers = {}; @@ -390,13 +390,15 @@ class _ApiService implements ApiService { _dio.options.baseUrl, baseUrl, ))); - final _result = await _dio.fetch>(_options); - late BaseData _value; + final _result = await _dio.fetch?>(_options); + late BaseData? _value; try { - _value = BaseData.fromJson( - _result.data!, - (json) => UserInfo.fromJson(json as Map), - ); + _value = _result.data == null + ? null + : BaseData.fromJson( + _result.data!, + (json) => UserInfo.fromJson(json as Map), + ); } on Object catch (e, s) { errorLogger?.logError(e, s, _options); rethrow; diff --git a/lib/setting/account_security_page.dart b/lib/setting/account_security_page.dart index 65fb86d3..8ac7bfd8 100644 --- a/lib/setting/account_security_page.dart +++ b/lib/setting/account_security_page.dart @@ -9,6 +9,7 @@ import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; class AccountSecurityPage extends StatefulWidget { @@ -25,28 +26,23 @@ class _AccountSecurityPage extends State { @override void initState() { super.initState(); - SmartDialog.showLoading(msg: S.current.zhengzaijiazai); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token") ?? "", - ), - queryUser(), - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token ?? "", + ); + queryUser(); } queryUser() async { - BaseData? baseDate = - await apiService?.queryInfo().catchError((onError) {}); - if (baseDate?.isSuccess ?? false) { - userInfo = baseDate!.data; + SmartDialog.showLoading(msg: S.current.zhengzaijiazai); + BaseData? baseDate = await apiService?.queryInfo().catchError((onError) { + return BaseData()..isSuccess = false; + }); + if ((baseDate?.isSuccess ?? false) && baseDate!.data != null) { + userInfo = baseDate.data; setState(() {}); - SharedPreferences.getInstance().then( - (value) => { - value.setString('user', jsonEncode(baseDate.data)), - }, - ); + SharedInstance.instance.saveUser(baseDate.data!); SmartDialog.dismiss(); } } @@ -63,7 +59,8 @@ class _AccountSecurityPage extends State { ), onTap: () { Navigator.of(context).pop(); - }), + }, + ), title: Text( S.of(context).zhanghaoanquan, style: TextStyle( @@ -77,8 +74,12 @@ class _AccountSecurityPage extends State { ), body: Container( decoration: new BoxDecoration( - border: - Border(bottom: BorderSide(color: Color(0xffF7F7F7), width: 0.0)), + border: Border( + bottom: BorderSide( + color: Color(0xffF7F7F7), + width: 0.0, + ), + ), color: Color(0xffF7F7F7), ), child: Column( @@ -88,12 +89,14 @@ class _AccountSecurityPage extends State { children: [ GestureDetector( onTap: () { - Navigator.of(context) - .pushNamed('/router/binding_phone_page', arguments: { - "userInfo": userInfo - }).then((value) => { - queryUser(), - }); + Navigator.of(context).pushNamed( + '/router/binding_phone_page', + arguments: { + "userInfo": userInfo + }, + ).then((value) => { + queryUser() + }); }, child: Container( padding: EdgeInsets.all(15), diff --git a/lib/setting/help_feedback_page.dart b/lib/setting/help_feedback_page.dart index 23d792fe..f514f5fd 100644 --- a/lib/setting/help_feedback_page.dart +++ b/lib/setting/help_feedback_page.dart @@ -6,6 +6,7 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/round_button.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -27,9 +28,7 @@ class _HelpFeedbackPage extends State { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = ApiService(Dio(), context: context, token: value.getString("token") ?? ""); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token ?? ""); } @@ -169,7 +168,8 @@ class _HelpFeedbackPage extends State { ), ], ), - )), + ), + ), ); } @@ -264,7 +264,7 @@ class _HelpFeedbackPage extends State { offset: Offset(0, 3), blurRadius: 14, spreadRadius: 0, - ) + ), ], ), child: Column( diff --git a/lib/setting/logout_ing.dart b/lib/setting/logout_ing.dart index 5b51e079..c16092bc 100644 --- a/lib/setting/logout_ing.dart +++ b/lib/setting/logout_ing.dart @@ -10,6 +10,7 @@ import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/border_text.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -45,18 +46,19 @@ class _LogoutIng extends State { } queryUserBalance() async { - SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService( Dio(), context: context, - token: value.getString("token") ?? "", + token: SharedInstance.instance.token, showLoading: false, ); - BaseData? baseData = await apiService?.queryInfo().catchError((onError) {}); + BaseData? baseData = await apiService?.queryInfo().catchError((onError) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { userInfo = baseData!.data; balance = userInfo?.balance ?? "0.00"; - money = userInfo?.money ??"0.00"; + money = userInfo?.money ?? "0.00"; phone = userInfo?.phone ?? ""; if (mounted) setState(() {}); } @@ -64,8 +66,10 @@ class _LogoutIng extends State { proving(mobile) async { if(phoneController.text != phone){ - SmartDialog.showToast("手机号码不正确", - alignment: Alignment.center); + SmartDialog.showToast( + "手机号码不正确", + alignment: Alignment.center, + ); return ; } if (_sendCodeStatus != 0) @@ -74,13 +78,17 @@ class _LogoutIng extends State { } sendProving(v) async{ - BaseData? baseData = await apiService?.sendVerify({"areaCode": "+86", "mobile": phoneController.text, "verification": v}).catchError((onError) {}); + BaseData? baseData = await apiService?.sendVerify({ + "areaCode": "+86", + "mobile": phoneController.text, + "verification": v, + }).catchError((onError) {}); if (baseData?.isSuccess ?? false) { countdown(); - SmartDialog.showToast(baseData!.data, - alignment: Alignment.center); - }else{ - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); + SmartDialog.showToast( + baseData!.data, + alignment: Alignment.center, + ); } } @@ -90,8 +98,7 @@ class _LogoutIng extends State { if (baseData?.isSuccess ?? false) { logOut(); SmartDialog.showToast(baseData!.data, alignment: Alignment.center); - }else{ - SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); + } else { Navigator.of(context).pop(); } } @@ -463,16 +470,11 @@ class _LogoutIng extends State { } logOut() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - sharedPreferences.setString("token", ""); - sharedPreferences.setString("user", ""); - sharedPreferences.setString("userJson", ""); - sharedPreferences.setString("userId", ""); - sharedPreferences.setString("mobile", ""); - sharedPreferences.setString("nick", ""); + SharedInstance.instance.logout(); - Navigator.of(context) - .pushNamedAndRemoveUntil('/router/new_login_page', (route) => false); + Navigator.of(context).pushNamedAndRemoveUntil( + '/router/new_login_page', (route) => false, + ); // if (xgFlutterPlugin != null) { // xgFlutterPlugin.stopXg(); // } diff --git a/lib/setting/setting_page.dart b/lib/setting/setting_page.dart index 7ddad3a9..d2388119 100644 --- a/lib/setting/setting_page.dart +++ b/lib/setting/setting_page.dart @@ -8,6 +8,7 @@ import 'package:huixiang/utils/ImgCachePath.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/round_button.dart'; import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -36,8 +37,7 @@ class _SettingPage extends State { } setLanguage() async { - SharedPreferences shared = await SharedPreferences.getInstance(); - locale = shared.getString('language') ?? "tw"; + locale = SharedInstance.instance.language ?? "tw"; if (mounted) setState(() {}); } @@ -236,9 +236,9 @@ class _SettingPage extends State { // } // } - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - List? miniAppids = sharedPreferences.getStringList("miniAppid"); - if (miniAppids != null && miniAppids.length > 0) { + + List miniAppids = SharedInstance.instance.miniAppids; + if (miniAppids.isNotEmpty) { miniAppids.forEach((element) async { print("appid: $element"); // await Min.closeCurrentApp(); @@ -252,7 +252,7 @@ class _SettingPage extends State { } AppUtils.deleteDirectory(Directory(filePath)); }); - sharedPreferences.setStringList("miniAppid", []); + SharedInstance.instance.saveMiniAppId([]); } AppUtils.deleteDirectory(Directory(ImgCachePath.instance.path)); @@ -270,35 +270,21 @@ class _SettingPage extends State { S.load(Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW')); locale = "tw"; eventBus.fire(EventType(1)); - }else { - S.load(Locale.fromSubtags(languageCode: 'en', countryCode: 'US')); - locale = "en"; - eventBus.fire(EventType(2)); + } else { + S.load(Locale.fromSubtags(languageCode: 'en', countryCode: 'US')); + locale = "en"; + eventBus.fire(EventType(2)); } - SharedPreferences.getInstance().then((value) => { - value.setString("language", language), - }); + SharedInstance.instance.saveLanguage(language); setState(() {}); Navigator.of(context).pop(); } logOut() async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - sharedPreferences.setString("token", ""); - sharedPreferences.setString("user", ""); - sharedPreferences.setString("userJson", ""); - sharedPreferences.setString("userId", ""); - sharedPreferences.setString("mobile", ""); - sharedPreferences.setString("nick", ""); - sharedPreferences.setString("account", ""); - sharedPreferences.setString("password", ""); - - - Navigator.of(context) - .pushNamedAndRemoveUntil('/router/new_login_page', (route) => false); - // if (xgFlutterPlugin != null) { - // xgFlutterPlugin.stopXg(); - // } + SharedInstance.instance.logout(); + Navigator.of(context).pushNamedAndRemoveUntil( + '/router/new_login_page', (route) => false, + ); } Widget settingItem(left, right) { diff --git a/lib/settlement/settlement.dart b/lib/settlement/settlement.dart index 4489e995..b71f3362 100644 --- a/lib/settlement/settlement.dart +++ b/lib/settlement/settlement.dart @@ -33,11 +33,10 @@ import 'package:huixiang/settlement/settlement_view/settlement_coupon.dart'; import 'package:huixiang/settlement/settlement_view/settlement_order_commodity.dart'; import 'package:huixiang/settlement/settlement_view/vip_discounts_select.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/round_button.dart'; -import 'package:shared_preferences/shared_preferences.dart'; - -import '../view_widget/settlement_tips_dialog.dart'; +import 'package:huixiang/view_widget/settlement_tips_dialog.dart'; class Settlement extends StatefulWidget { final arguments; @@ -129,85 +128,86 @@ class _Settlement extends State { placeOrder = true; } - SharedPreferences.getInstance().then((value) { - String minToken = value.getString("minToken") ?? ""; - String tenant = value.getString("tenant") ?? ""; - String storeId = value.getString("storeId") ?? ""; - minService = MinApiService(Dio(), - context: context, - token: minToken, - tenant: tenant, - storeId: storeId, - showLoading: false); - queryMemberInfo(); - if (widget.arguments["pid"] != null && - widget.arguments["pid"] != "" && - tableId <= 0) { - queryOrderInfo( - address != null ? address!.id : null, - ((storeInfo?.pickupType?.dineInTakeStatus ?? false) == true && - (subscribeParam?.isEnableSubscribe ?? false) == false && - selectedBtn != 1 && - selectedBtn != 2) - ? diningStatus - : selectedBtn, - 0, - 0, - widget.arguments["pid"] ?? (productId ?? 0), - productSkuId ?? "", - actProductId ?? "", - actProductSkuId ?? "", - "AUTO", - // useVipPriceSelect, - // useBenefitSelect, - count1, - payChannel, - tableId); - } else if (widget.arguments["cid"] != null && - widget.arguments["cid"] != "" && - tableId <= 0) { - queryOrderInfo( - address != null ? address!.id : null, - ((storeInfo?.pickupType?.dineInTakeStatus ?? false) == true && - (subscribeParam?.isEnableSubscribe ?? false) == false && - selectedBtn != 1 && - selectedBtn != 2) - ? diningStatus - : selectedBtn, - widget.arguments["cid"] ?? 0, - 0, - productId ?? 0, - productSkuId ?? "", - actProductId ?? "", - actProductSkuId ?? "", - "AUTO", - // useVipPriceSelect, - // useBenefitSelect, - count1, - payChannel, - tableId); - } else - queryOrderInfo( - null, - ((storeInfo?.pickupType?.dineInTakeStatus ?? false) && - !(subscribeParam?.isEnableSubscribe ?? false) && - selectedBtn != 1 && - selectedBtn != 2) - ? diningStatus - : selectedBtn, - 0, - 0, - productId ?? 0, - productSkuId ?? "", - actProductId ?? "", - actProductSkuId ?? "", - "AUTO", - // useVipPriceSelect, - // (useVipPriceSelect == true && isVips) ? false:useBenefitSelect, - count1, - payChannel, - tableId); - }); + String minToken = SharedInstance.instance.miniToken; + String tenant = SharedInstance.instance.tenant; + String storeId = SharedInstance.instance.storeId; + minService = MinApiService(Dio(), + context: context, + token: minToken, + tenant: tenant, + storeId: storeId, + showLoading: false); + + queryMemberInfo(); + if (widget.arguments["pid"] != null && + widget.arguments["pid"] != "" && + tableId <= 0) { + queryOrderInfo( + address != null ? address!.id : null, + ((storeInfo?.pickupType?.dineInTakeStatus ?? false) == true && + (subscribeParam?.isEnableSubscribe ?? false) == false && + selectedBtn != 1 && + selectedBtn != 2) + ? diningStatus + : selectedBtn, + 0, + 0, + widget.arguments["pid"] ?? (productId ?? 0), + productSkuId ?? "", + actProductId ?? "", + actProductSkuId ?? "", + "AUTO", + // useVipPriceSelect, + // useBenefitSelect, + count1, + payChannel, + tableId); + } else if (widget.arguments["cid"] != null && + widget.arguments["cid"] != "" && + tableId <= 0) { + queryOrderInfo( + address != null ? address!.id : null, + ((storeInfo?.pickupType?.dineInTakeStatus ?? false) == true && + (subscribeParam?.isEnableSubscribe ?? false) == false && + selectedBtn != 1 && + selectedBtn != 2) + ? diningStatus + : selectedBtn, + widget.arguments["cid"] ?? 0, + 0, + productId ?? 0, + productSkuId ?? "", + actProductId ?? "", + actProductSkuId ?? "", + "AUTO", + // useVipPriceSelect, + // useBenefitSelect, + count1, + payChannel, + tableId, + ); + } else + queryOrderInfo( + null, + ((storeInfo?.pickupType?.dineInTakeStatus ?? false) && + !(subscribeParam?.isEnableSubscribe ?? false) && + selectedBtn != 1 && + selectedBtn != 2) + ? diningStatus + : selectedBtn, + 0, + 0, + productId ?? 0, + productSkuId ?? "", + actProductId ?? "", + actProductSkuId ?? "", + "AUTO", + // useVipPriceSelect, + // (useVipPriceSelect == true && isVips) ? false:useBenefitSelect, + count1, + payChannel, + tableId, + ); fluwx.addSubscriber((response) { print("payCallback: ${response.errCode}"); @@ -238,7 +238,9 @@ class _Settlement extends State { "buyNum": buyNum, "payChannel": payChannel, "tableId": tableId - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); this.promotion = null; promotions = ""; this.couponListBean = null; @@ -308,13 +310,10 @@ class _Settlement extends State { queryMemberInfo() async { BaseData? baseData = await minService?.memberInfo().catchError((error) { debugPrint("${error}"); + return BaseData()..isSuccess = false; }); - if (baseData?.isSuccess ?? false) { - SharedPreferences.getInstance().then( - (value) => { - value.setString('minMember', jsonEncode(baseData!.data)), - }, - ); + if ((baseData?.isSuccess ?? false) && baseData?.data != null) { + SharedInstance.instance.saveMiniMember(jsonEncode(baseData!.data)); } } @@ -325,28 +324,27 @@ class _Settlement extends State { ); BaseData? baseData = await minService?.getOrderDetails({ "id": pageType != null ? widget.arguments["orderId"] : id ?? parentId, - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { minOrderInfo = baseData!.data; coupons = minOrderInfo?.couponName ?? ""; }); - SmartDialog.dismiss(); - } else { - SmartDialog.showToast(baseData?.msg ?? "", alignment: Alignment.center); - SmartDialog.dismiss(); } + SmartDialog.dismiss(); } ///取消优惠券 queryCancelMemberCoupon(orderId) async { - BaseData? baseData = - await minService?.cancelMemberCoupon(orderId).catchError((error) {}); + BaseData? baseData = await minService?.cancelMemberCoupon(orderId) + .catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { queryOrderDetails(parentId); // SmartDialog.showToast(baseData.data, alignment: Alignment.center); - } else { - SmartDialog.showToast(baseData?.msg ?? "", alignment: Alignment.center); } } @@ -356,11 +354,11 @@ class _Settlement extends State { "memberCouponId": memberCouponId, "orderId": parentId, "phone": minOrderInfo?.orderInfoVo?.memberVO?.phone - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { queryOrderDetails(parentId); - } else { - SmartDialog.showToast(baseData?.msg ?? "", alignment: Alignment.center); } } @@ -391,8 +389,7 @@ class _Settlement extends State { tableId); return; } - BaseListData
? baseDate = - await minService?.queryAddress().catchError((error) { + BaseListData
? baseDate = await minService?.queryAddress().catchError((error) { return BaseListData
()..isSuccess = false; }); @@ -472,8 +469,9 @@ class _Settlement extends State { ///选择收货地址 selectedAddress(String addId) async { - BaseListData
? baseDate = - await minService?.queryAddress().catchError((error) {}); + BaseListData
? baseDate = await minService?.queryAddress().catchError((error) { + return BaseListData
()..isSuccess = false; + }); if (baseDate?.isSuccess ?? false) { setState(() { baseDate!.data?.forEach((element) { @@ -509,7 +507,7 @@ class _Settlement extends State { ///发起活动 queryLaunchAct() async { - BaseData? baseData = await minService?.launchAct({ + BaseData? baseData = await minService?.launchAct({ "actProductId": activityDetails?.actProduct?.id, "actRecordId": 0, "actTemplateId": activityDetails?.actProduct?.templateId, @@ -524,7 +522,9 @@ class _Settlement extends State { "skuId": actProductSkuId ?? "", "skuPrice": settleOrderInfo?.price, "templateType": pageType, - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { setState(() { launchJoinAct = baseData!.data; @@ -542,7 +542,7 @@ class _Settlement extends State { ///参与活动 queryJoinAct() async { - BaseData? baseData = await minService?.joinAct({ + BaseData? baseData = await minService?.joinAct({ "actProductId": activityDetails?.actProduct?.id, "actRecordId": widget.arguments["indexP"], "actTemplateId": activityDetails?.actProduct?.templateId, @@ -557,12 +557,12 @@ class _Settlement extends State { "skuId": actProductSkuId ?? "", "skuPrice": skuPrice1, "templateType": pageType - }).catchError((error) {}); + }).catchError((error) { + return BaseData()..isSuccess = false; + }); if (baseData?.isSuccess ?? false) { launchJoinAct = baseData!.data; activityPay(); - } else { - SmartDialog.showToast(baseData?.msg ?? "", alignment: Alignment.center); } } @@ -650,7 +650,7 @@ class _Settlement extends State { BaseData? baseData = await minService ?.placeOrderFirst(placeOrderFirst!.toJson()) .catchError((error) { - print("error: $error"); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { placeOrder = true; @@ -674,14 +674,14 @@ class _Settlement extends State { baseData = await minService ?.placeOrderFirst(placeOrderFirst!.toJson()) .catchError((error) { - print("error: $error"); + return BaseData()..isSuccess = false; }); } else { //加菜 baseData = await minService ?.addOrder(placeOrderFirst!.toJson()) .catchError((error) { - print("error: $error"); + return BaseData()..isSuccess = false; }); } } @@ -728,7 +728,7 @@ class _Settlement extends State { BaseData? baseData = await minService ?.settlementWx(placeOrderFirst!.toJson()) .catchError((error) { - print(error); + return BaseData()..isSuccess = false; }); // orderButton = false; if (baseData?.isSuccess ?? false) { @@ -762,11 +762,10 @@ class _Settlement extends State { BaseData? baseData = await minService ?.settlementApi(placeOrderFirst!.toJson()) .catchError((error) { - print(error); + return BaseData()..isSuccess = false; }); // orderButton = false; if (baseData?.isSuccess ?? false) { - // SmartDialog.showToast(baseData.data, alignment: Alignment.center); toOrderDetails(placeOrderFirst!.id); } else { SmartDialog.show( @@ -800,7 +799,7 @@ class _Settlement extends State { bargainOrderId != null ? bargainOrderId! : launchJoinAct?.orderId, "payChannel": placeOrderFirst!.payChannel }).catchError((error) { - print(error); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { WxPay? wxPay = baseData!.data; @@ -824,12 +823,12 @@ class _Settlement extends State { )); } } else { - BaseData? baseData = await minService?.actPay({ + BaseData? baseData = await minService?.actPay({ "orderId": bargainOrderId != null ? bargainOrderId : launchJoinAct?.orderId, "payChannel": payChannel }).catchError((error) { - print(error); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { toOrderDetails( @@ -943,7 +942,7 @@ class _Settlement extends State { // useBenefitSelect, count1, payChannel, - tableId ?? 0); + tableId); }, queryAddress, storeInfo, @@ -1630,19 +1629,19 @@ class _Settlement extends State { selectedBtn != 2) ? diningStatus : selectedBtn, - (((pro?.id ?? 0) ?? (productId ?? 0)) == 0 && + ((pro?.id ?? productId ?? "0") == "0" && (couponListBean?.id ?? 0) != 0) ? couponListBean?.id : 0, 0, - (((pro?.id ?? 0) ?? (productId ?? 0)) == 0 && + ((pro?.id ?? productId ?? "0") == "0" && (couponListBean?.id ?? 0) != 0) ? 0 - : ((pro?.id ?? 0) ?? productId), + : (pro?.id ?? productId ?? "0"), productSkuId ?? "", actProductId ?? "", actProductSkuId ?? "", - (((pro?.id ?? 0) ?? (productId ?? 0)) == 0 + ((pro?.id ?? productId ?? 0) == 0 ? ((couponListBean?.id ?? 0) != 0 ? "COUPON" : "AUTO") : "ACTIVITY"), // useVipPriceSelect, diff --git a/lib/settlement/settlement_view/pay_method.dart b/lib/settlement/settlement_view/pay_method.dart index bda99c7e..1e8346ef 100644 --- a/lib/settlement/settlement_view/pay_method.dart +++ b/lib/settlement/settlement_view/pay_method.dart @@ -5,6 +5,7 @@ import 'package:huixiang/data/min_order_info.dart'; import 'package:huixiang/data/settle_order_info.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; class PayMethod extends StatefulWidget { @@ -35,16 +36,15 @@ class _PayMethod extends State { void initState() { super.initState(); checkIndex = ((widget.minOrderInfo != null) ? (widget.minOrderInfo?.isRaise??false) : (widget.settleOrderInfo?.isRaise ?? false)) ? 4:5; - SharedPreferences.getInstance().then((value) { - if (value.getString("minMember")?.isNotEmpty ?? false) { - Map memberInfo = jsonDecode(value.getString("minMember")!); - balance = memberInfo["balance"]; - money = memberInfo["money"]; - mGreenMoney = memberInfo["greenMoney"]; - mRaiseMoney = memberInfo["raiseMoney"]; - setState(() {}); - } - }); + + if (SharedInstance.instance.minMember.isNotEmpty) { + Map memberInfo = jsonDecode(SharedInstance.instance.minMember); + balance = memberInfo["balance"]; + money = memberInfo["money"]; + mGreenMoney = memberInfo["greenMoney"]; + mRaiseMoney = memberInfo["raiseMoney"]; + setState(() {}); + } } @override @@ -89,15 +89,15 @@ class _PayMethod extends State { ), ), ), - if(widget.tableId > 0 ? !(widget?.minOrderInfo?.isRaise ?? false) : !(widget?.settleOrderInfo?.isRaise ?? false)) + if(widget.tableId > 0 ? !(widget.minOrderInfo?.isRaise ?? false) : !(widget.settleOrderInfo?.isRaise ?? false)) GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - double m = double.parse(money); + double? m = double.tryParse(money); if (m == null) { m = 0; } - double orderSum = double.parse(widget.settleOrderInfo?.orderSum ?? '0'); + double? orderSum = double.tryParse(widget.settleOrderInfo?.orderSum ?? '0'); if (orderSum == null) { orderSum = 0; } @@ -113,7 +113,7 @@ class _PayMethod extends State { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - checkView(1, isHide: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(money) ?? 0)), + checkView(1, isHide: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(money) ?? 0)), Expanded( child: Container(), flex: 1, @@ -123,7 +123,7 @@ class _PayMethod extends State { style: TextStyle( fontSize: 14.sp, fontFamily: 'JDZhengHT', - color: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(money) ?? 0) ? Color(0x66353535) : Color(0xff353535), + color: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(money) ?? 0) ? Color(0x66353535) : Color(0xff353535), fontWeight: MyFontWeight.medium, ), ), @@ -134,26 +134,26 @@ class _PayMethod extends State { S.of(context).huixiangqianbao, style: TextStyle( fontSize: 14.sp, - color: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(money) ?? 0) ? Color(0x66353535) : Color(0xff353535), + color: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(money) ?? 0) ? Color(0x66353535) : Color(0xff353535), fontWeight: MyFontWeight.semi_bold, ), ), ], ), ), - if(widget.tableId > 0 ? !(widget?.minOrderInfo?.isRaise ?? false) : !(widget?.settleOrderInfo?.isRaise ?? false)) + if(widget.tableId > 0 ? !(widget.minOrderInfo?.isRaise ?? false) : !(widget.settleOrderInfo?.isRaise ?? false)) SizedBox( height: 10, ), - if(widget.tableId > 0 ? !(widget?.minOrderInfo?.isRaise ?? false) : !(widget?.settleOrderInfo?.isRaise ?? false)) + if(widget.tableId > 0 ? !(widget.minOrderInfo?.isRaise ?? false) : !(widget.settleOrderInfo?.isRaise ?? false)) GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - double balanceMoney = double.parse(balance); + double? balanceMoney = double.tryParse(balance); if (balanceMoney == null) { balanceMoney = 0; } - double orderSum = double.parse(widget.settleOrderInfo?.orderSum ?? '0'); + double? orderSum = double.tryParse(widget.settleOrderInfo?.orderSum ?? '0'); if (orderSum == null) { orderSum = 0; } @@ -169,7 +169,7 @@ class _PayMethod extends State { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - checkView(2, isHide: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(balance) ?? 0)), + checkView(2, isHide: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(balance) ?? 0)), Expanded( child: Container(), flex: 1, @@ -179,7 +179,7 @@ class _PayMethod extends State { style: TextStyle( fontSize: 14.sp, fontFamily: 'JDZhengHT', - color: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(balance) ?? 0) ? Color(0x66353535) : Color(0xff353535), + color: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(balance) ?? 0) ? Color(0x66353535) : Color(0xff353535), fontWeight: MyFontWeight.medium, ), ), @@ -190,26 +190,26 @@ class _PayMethod extends State { S.of(context).mendianyue, style: TextStyle( fontSize: 14.sp, - color: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(balance) ?? 0) ? Color(0x66353535) : Color(0xff353535), + color: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(balance) ?? 0) ? Color(0x66353535) : Color(0xff353535), fontWeight: MyFontWeight.semi_bold, ), ), ], ), ), - if(widget.tableId > 0 ? !(widget?.minOrderInfo?.isRaise ?? false) : !(widget?.settleOrderInfo?.isRaise ?? false)) + if(widget.tableId > 0 ? !(widget.minOrderInfo?.isRaise ?? false) : !(widget.settleOrderInfo?.isRaise ?? false)) SizedBox( height: 10, ), - if(mGreenMoney!="0.00" && (widget.tableId > 0 ? !(widget?.minOrderInfo?.isRaise ?? false) : !(widget?.settleOrderInfo?.isRaise ?? false))) + if(mGreenMoney!="0.00" && (widget.tableId > 0 ? !(widget.minOrderInfo?.isRaise ?? false) : !(widget.settleOrderInfo?.isRaise ?? false))) GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - double greenMoney = double.parse(mGreenMoney); + double? greenMoney = double.tryParse(mGreenMoney); if (greenMoney == null) { greenMoney = 0; } - double orderSum = double.parse(widget.settleOrderInfo?.orderSum ?? '0'); + double? orderSum = double.tryParse(widget.settleOrderInfo?.orderSum ?? '0'); if (orderSum == null) { orderSum = 0; } @@ -218,19 +218,6 @@ class _PayMethod extends State { } setState(() { checkIndex = 3; - // if(widget.promotions != "" || widget.coupons != "" || widget.useVipPriceSelect || widget.useBenefitSelect){ - // print("discount-promotions: ${widget.promotions}"); - // print("discount-coupons: ${widget.coupons}"); - // print("discount-useVipPriceSelect: ${widget.useVipPriceSelect}"); - // print("discount-useBenefitSelect: ${widget.useBenefitSelect}"); - // SmartDialog.show( - // widget: SettlementTips( - // () { - // }, - // text: "绿币支付不参与任何活动优惠,请重新选择支付方式", - // )); - // return; - // } }); print("discount-payChannelCheck: 5"); widget.payChannelCheck(5); @@ -239,14 +226,14 @@ class _PayMethod extends State { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - checkView(3, isHide: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(mGreenMoney) ?? 0)), + checkView(3, isHide: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(mGreenMoney) ?? 0)), Spacer(flex: 1,), Text( "¥$mGreenMoney", style: TextStyle( fontSize: 14.sp, fontFamily: 'JDZhengHT', - color: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(mGreenMoney) ?? 0) ? Color(0x66353535) : Color(0xff353535), + color: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(mGreenMoney) ?? 0) ? Color(0x66353535) : Color(0xff353535), fontWeight: MyFontWeight.medium, ), ), @@ -257,26 +244,26 @@ class _PayMethod extends State { S.of(context).lvbizhifu, style: TextStyle( fontSize: 14.sp, - color: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(mGreenMoney) ?? 0) ? Color(0x66353535) : Color(0xff353535), + color: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(mGreenMoney) ?? 0) ? Color(0x66353535) : Color(0xff353535), fontWeight: MyFontWeight.semi_bold, ), ), ], ), ), - if(mGreenMoney != "0.00" && (widget.tableId > 0 ? !(widget?.minOrderInfo?.isRaise ?? false) : !(widget?.settleOrderInfo?.isRaise ?? false))) + if(mGreenMoney != "0.00" && (widget.tableId > 0 ? !(widget.minOrderInfo?.isRaise ?? false) : !(widget.settleOrderInfo?.isRaise ?? false))) SizedBox( height: 10, ), - if(mRaiseMoney != "0" && (widget.tableId > 0 ? (widget?.minOrderInfo?.isRaise ?? false) : (widget?.settleOrderInfo?.isRaise ?? false))) + if(mRaiseMoney != "0" && (widget.tableId > 0 ? (widget.minOrderInfo?.isRaise ?? false) : (widget.settleOrderInfo?.isRaise ?? false))) GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - double raiseMoney = double.parse(mRaiseMoney); + double? raiseMoney = double.tryParse(mRaiseMoney); if (raiseMoney == null) { raiseMoney = 0; } - double orderSum = double.parse(widget.settleOrderInfo?.orderSum ?? '0'); + double? orderSum = double.tryParse(widget.settleOrderInfo?.orderSum ?? '0'); if (orderSum == null) { orderSum = 0; } @@ -285,15 +272,6 @@ class _PayMethod extends State { } setState(() { checkIndex = 4; - // if(widget.promotions != "" || widget.coupons != "" || widget.useVipPriceSelect || widget.useBenefitSelect){ - // SmartDialog.show( - // widget: SettlementTips( - // () {}, - // text: "助农积分不参与任何活动优惠,请重新选择支付方式", - // ), - // ); - // return; - // } }); widget.payChannelCheck(7); }, @@ -301,7 +279,7 @@ class _PayMethod extends State { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - checkView(4, isHide: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(mRaiseMoney) ?? 0)), + checkView(4, isHide: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(mRaiseMoney) ?? 0)), Spacer( flex: 1, ), @@ -310,7 +288,7 @@ class _PayMethod extends State { style: TextStyle( fontSize: 14.sp, fontFamily: 'JDZhengHT', - color: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(mRaiseMoney) ?? 0) ? Color(0x66353535) : Color(0xff353535), + color: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(mRaiseMoney) ?? 0) ? Color(0x66353535) : Color(0xff353535), fontWeight: MyFontWeight.medium, ), ), @@ -321,16 +299,15 @@ class _PayMethod extends State { S.of(context).zhunongjifen, style: TextStyle( fontSize: 14.sp, - color: (double.parse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.parse(mRaiseMoney) ?? 0) ? Color(0x66353535) : Color(0xff353535), + color: (double.tryParse(widget.settleOrderInfo?.orderSum ?? '0') ?? 0) > (double.tryParse(mRaiseMoney) ?? 0) ? Color(0x66353535) : Color(0xff353535), fontWeight: MyFontWeight.semi_bold, ), ), ], ), ), - if(mRaiseMoney !="0" && (widget.tableId > 0 ? !(widget?.minOrderInfo?.isRaise ?? false) : !(widget?.settleOrderInfo?.isRaise ?? false))) - - if(widget.tableId > 0 ? !(widget?.minOrderInfo?.isRaise ?? false) : !(widget?.settleOrderInfo?.isRaise ?? false)) + if(mRaiseMoney !="0" && (widget.tableId > 0 ? !(widget.minOrderInfo?.isRaise ?? false) : !(widget.settleOrderInfo?.isRaise ?? false))) + if(widget.tableId > 0 ? !(widget.minOrderInfo?.isRaise ?? false) : !(widget.settleOrderInfo?.isRaise ?? false)) GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { @@ -368,7 +345,6 @@ class _PayMethod extends State { var checkIndex = 5; Widget checkView(var index, {bool isHide = false}) { - if (isHide) { return Container( padding: EdgeInsets.only(right:36.w), diff --git a/lib/store/report_assess .dart b/lib/store/report_assess .dart index d175088a..0849686b 100644 --- a/lib/store/report_assess .dart +++ b/lib/store/report_assess .dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -28,11 +29,7 @@ class _ReportAssess extends State { @override void initState() { super.initState(); - - SharedPreferences.getInstance().then((value) { - apiService = ApiService(Dio(), - context: context, token: value.getString("token") ?? "", pay: true); - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token ?? "", pay: true); } @override @@ -63,7 +60,7 @@ class _ReportAssess extends State { color: Color(0xFFFFFFFF), ), ), - ) + ), ], ), body: SmartRefresher( @@ -108,66 +105,6 @@ class _ReportAssess extends State { ), ), ); - // Scaffold( - // appBar: MyAppBar( - // title: "发布评价", - // titleColor: Colors.black, - // titleSize: 17.sp, - // background: Color(0xFFFFFFFF), - // leadingColor: Colors.black, - // actions: [ - // Container( - // width: 46.w, - // margin: EdgeInsets.only(right: 14,top: 14,bottom: 14), - // decoration: BoxDecoration( - // color: Color(0xFFB3B3B3), - // borderRadius: BorderRadius.circular(4), - // ), - // alignment: Alignment.center, - // child: Text( - // S.of(context).fabu, - // style: TextStyle( - // fontWeight: MyFontWeight.bold, - // fontSize: 14.sp, - // color: Color(0xFFFFFFFF), - // ), - // ), - // ) - // ], - // ), - // body: Container( - // height: double.infinity, - // color: Color(0xFFFFFFFF), - // child: Stack( - // children: [ - // Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // mainAxisAlignment: MainAxisAlignment.start, - // children: [ - // Container( - // width: double.infinity, - // height: 1.h, - // color: Color(0xFFF2F2F2), - // ), - // SingleChildScrollView( - // physics: BouncingScrollPhysics(), - // child: Container( - // // margin: EdgeInsets.only(left: 14, right: 14, top: 13.h), - // child:Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // mainAxisAlignment: MainAxisAlignment.start, - // children: [ - // goodsAssessList(), - // ], - // ), - // ), - // ) - // ], - // ), - // ], - // ), - // ), - // ); } ///评价列表 @@ -244,7 +181,8 @@ class _ReportAssess extends State { ), ], ), - )), + ), + ), ], ), goodsAssess(), @@ -311,7 +249,8 @@ class _ReportAssess extends State { ), ), ], - )), + ), + ), Expanded( child: Column( children: [ @@ -329,7 +268,8 @@ class _ReportAssess extends State { ), ), ], - )), + ), + ), ], ) ], diff --git a/lib/store/shop/shop_scroll_controller.dart b/lib/store/shop/shop_scroll_controller.dart new file mode 100644 index 00000000..6ff1c3f2 --- /dev/null +++ b/lib/store/shop/shop_scroll_controller.dart @@ -0,0 +1,215 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +import 'shop_scroll_coordinator.dart'; +import 'shop_scroll_position.dart'; + +/// 滑动控制器。为可滚动小部件创建一个控制器。 +/// +/// [initialScrollOffset] 和 [keepScrollOffset] 的值不能为 null。 +class ShopScrollController extends ScrollController { + ShopScrollController( + this.coordinator, { + double initialScrollOffset = 0.0, + + /// 每次滚动完成时,请使用 [PageStorage] 保存当前滚动 [offset] ,如果重新创建了此 + /// 控制器的可滚动内容,则将其还原。 + /// + /// 如果将此属性设置为false,则永远不会保存滚动偏移量, + /// 并且始终使用 [initialScrollOffset] 来初始化滚动偏移量。如果为 true(默认值), + /// 则第一次创建控制器的可滚动对象时将使用初始滚动偏移量,因为尚无要还原的滚动偏移量。 + /// 随后,将恢复保存的偏移,并且忽略[initialScrollOffset]。 + /// + /// 也可以看看: + /// * [PageStorageKey],当同一路径中出现多个滚动条时,应使用 [PageStorageKey] + /// 来区分用于保存滚动偏移量的 [PageStorage] 位置。 + bool keepScrollOffset = true, + + /// [toString] 输出中使用的标签。帮助在调试输出中标识滚动控制器实例。 + String debugLabel = 'ShopScrollController', + }) : _initialScrollOffset = initialScrollOffset, + super(keepScrollOffset: keepScrollOffset, debugLabel: debugLabel); + + final ShopScrollCoordinator coordinator; + + /// 用于 [offset] 的初始值。 + /// 如果 [keepScrollOffset] 为 false 或尚未保存滚动偏移量, + /// 则创建并附加到此控制器的新 [ShopScrollPosition] 对象的偏移量将初始化为该值。 + /// 默认为 0.0。 + @override + double get initialScrollOffset => _initialScrollOffset; + final double _initialScrollOffset; + + /// 当前附加的 [positions]。 + /// + /// 不应直接突变。 + /// 可以使用 [attach] 和 [detach] 添加和删除 [ShopScrollPosition] 对象。 + @protected + @override + Iterable get positions => _positions; + final List _positions = []; + + /// 是否有任何 [ShopScrollPosition] 对象已使用 [attach] 方法 + /// 将自身附加到 [ScrollController]。 + /// + /// 如果为 false,则不得调用与 [ShopScrollPosition] 交互的成员, + /// 例如 [position],[offset],[animateTo] 和 [jumpTo]。 + @override + bool get hasClients => _positions.isNotEmpty; + + /// 返回附加的[ScrollPosition],可以从中获取[ScrollView]的实际滚动偏移量。 + /// + /// 仅在仅连接一个 [position] 时调用此选项才有效。 + @override + ShopScrollPosition get position { + assert(_positions.isNotEmpty, + 'ScrollController not attached to any scroll views.'); + assert(_positions.length == 1, + 'ScrollController attached to multiple scroll views.'); + return _positions.single; + } + + /// 可滚动小部件的当前滚动偏移量。要求控制器仅控制一个可滚动小部件。 + @override + double get offset => position.pixels; + + /// 从当前位置到给定值的位置动画。 + /// 任何活动的动画都将被取消。 如果用户当前正在滚动,则该操作将被取消。 + /// 返回的 [Future] 将在动画结束时完成,无论它是否成功完成或是否被过早中断。 + /// + /// 每当用户尝试手动滚动或启动其他活动,或者动画到达视口边缘并尝试过度滚动时, + /// 动画都会中断。如果 [ShopScrollPosition] 不会过度滚动,而是允许滚动超出范围, + /// 那么超出范围不会中断动画。 + /// + /// 动画对视口或内容尺寸的更改无动于衷。 + /// + /// 一旦动画完成,如果滚动位置的值不稳定,则滚动位置将尝试开始弹道活动。 + /// (例如,如果滚动超出范围,并且在这种情况下滚动位置通常会弹回) + /// + /// 持续时间不能为零。要在没有动画的情况下跳至特定值,请使用 [jumpTo]。 + @override + Future animateTo( + double offset, { + required Duration duration, + required Curve curve, + }) { + assert( + _positions.isNotEmpty, + 'ScrollController not attached to any scroll views.', + ); + final List> animations = >[]; + for (int i = 0; i < _positions.length; i += 1) + animations[i] = _positions[i].animateTo( + offset, + duration: duration, + curve: curve, + ); + return Future.wait(animations).then((List _) => null); + } + + /// 将滚动位置从其当前值跳转到给定值,而不进行动画处理,也无需检查新值是否在范围内。 + /// 任何活动的动画都将被取消。 如果用户当前正在滚动,则该操作将被取消。 + /// + /// 如果此方法更改了滚动位置,则将分派开始/更新/结束滚动通知的序列。 + /// 此方法不能生成过滚动通知。跳跃之后,如果数值超出范围,则立即开始弹道活动。 + @override + void jumpTo(double value) { + assert( + _positions.isNotEmpty, + 'ScrollController not attached to any scroll views.', + ); + for (final ScrollPosition position in List.from(_positions)) + position.jumpTo(value); + } + + /// 在此控制器上注册给定位置。 + /// 此函数返回后,此控制器上的 [animateTo] 和 [jumpTo] 方法将操纵给定位置。 + @override + void attach(covariant ShopScrollPosition position) { + assert(!_positions.contains(position)); + _positions.add(position); + position.addListener(notifyListeners); + } + + /// 用此控制器注销给定位置。 + /// 此函数返回后,此控制器上的 [animateTo] 和 [jumpTo] 方法将不会操纵给定位置。 + @override + void detach(ScrollPosition position) { + assert(_positions.contains(position)); + position.removeListener(notifyListeners); + _positions.remove(position); + } + + @override + void dispose() { + for (final ScrollPosition position in _positions) + position.removeListener(notifyListeners); + super.dispose(); + } + + /// 创建一个 [ShopScrollPosition] 供 [Scrollable] 小部件使用。 + /// + /// 子类可以重写此功能,以自定义其控制的可滚动小部件使用的 [ShopScrollPosition]。 + /// 例如,[PageController] 重写此函数以返回面向页面的滚动位置子类, + /// 该子类在可滚动窗口小部件调整大小时保持同一页面可见。 + /// + /// 默认情况下,返回 [ScrollPositionWithSingleContext]。 + /// 参数通常传递给正在创建的 [ScrollPosition]: + /// + /// * [physics]:[ScrollPhysics] 的一个实例,它确定 [ScrollPosition] 对用户交互的 + /// 反应方式,释放或甩动时如何模拟滚动等。该值不会为null。它通常来自 [ScrollView] + /// 或其他创建 [Scrollable]的小部件, + /// 或者(如果未提供)来自环境的 [ScrollConfiguration]。 + /// * [context]:一个 [ScrollContext],用于与拥有 [ScrollPosition] 的对象进行通信 + /// (通常是 [Scrollable] 本身)。 + /// * [oldPosition]:如果这不是第一次为此 [Scrollable] 创建 [ScrollPosition],则 + /// 它将是前一个实例。当环境已更改并且 [Scrollable] 需要重新创建 [ScrollPosition] + /// 对象时,将使用此方法。 第一次创建 [ScrollPosition] 时为 null。 + @override + ShopScrollPosition createScrollPosition( + ScrollPhysics physics, + ScrollContext context, + ScrollPosition? oldPosition, + ) { + return ShopScrollPosition( + coordinator: coordinator, + physics: physics, + context: context, + initialPixels: initialScrollOffset, + keepScrollOffset: keepScrollOffset, + oldPosition: oldPosition, + debugLabel: debugLabel ?? "", + ); + } + + @override + String toString() { + final List description = []; + debugFillDescription(description); + return '${describeIdentity(this)}(${description.join(", ")})'; + } + + /// 在给定的描述中添加其他信息,以供 [toString] 使用。 + /// 此方法使子类更易于协调以提供高质量的 [toString] 实现。[ScrollController] 基类上 + /// 的 [toString] 实现调用 [debugFillDescription] 来从子类中收集有用的信息,以合并 + /// 到其返回值中。如果您重写了此方法,请确保通过调用 + /// `super.debugFillDescription)description)` 来启动方法。 + @override + @mustCallSuper + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (debugLabel != null) { + description.add(debugLabel!); + } + if (initialScrollOffset != 0.0) + description.add('initialScrollOffset: ${initialScrollOffset.toStringAsFixed(1)}, '); + if (_positions.isEmpty) { + description.add('no clients'); + } else if (_positions.length == 1) { + // 实际上不列出客户端本身,因为它的 toString 可能引用了我们。 + description.add('one client, offset ${offset.toStringAsFixed(1)}'); + } else { + description.add('${_positions.length} clients'); + } + } +} diff --git a/lib/store/shop/shop_scroll_coordinator.dart b/lib/store/shop/shop_scroll_coordinator.dart new file mode 100644 index 00000000..64223c30 --- /dev/null +++ b/lib/store/shop/shop_scroll_coordinator.dart @@ -0,0 +1,117 @@ +import 'dart:math' as math; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +import 'shop_scroll_controller.dart'; +import 'shop_scroll_position.dart'; + +enum PageExpandState { NotExpand, Expanding, Expanded } + +/// 协调器 +/// +/// 页面 Primary [CustomScrollView] 控制 +class ShopScrollCoordinator { + final String pageLabel = 'page'; + + ShopScrollController? _pageScrollController; + double Function()? pinnedHeaderSliverHeightBuilder; + + ShopScrollPosition get _pageScrollPosition => _pageScrollController!.position; + + ScrollDragController? scrollDragController; + + /// 主页面滑动部件默认位置 + double? _pageInitialOffset; + + /// 获取主页面滑动控制器 + ShopScrollController? pageScrollController([double initialOffset = 0.0]) { + _pageInitialOffset = initialOffset; + _pageScrollController = ShopScrollController( + this, + debugLabel: pageLabel, + initialScrollOffset: initialOffset, + ); + return _pageScrollController; + } + + /// 创建并获取一个子滑动控制器 + ShopScrollController newChildScrollController([String? debugLabel]) => ShopScrollController(this, debugLabel: debugLabel ?? ""); + + /// 子部件滑动数据协调 + /// + /// [userScrollDirection] 用户滑动方向 + /// [position] 被滑动的子部件的位置信息 + void applyUserOffset(double delta, [ScrollDirection? userScrollDirection, ShopScrollPosition? position,]) { + if (userScrollDirection == ScrollDirection.reverse) { + updateUserScrollDirection(_pageScrollPosition, userScrollDirection!); + final double? innerDelta = _pageScrollPosition.applyClampedDragUpdate(delta); + if (innerDelta != 0.0 && innerDelta != null) { + updateUserScrollDirection(position, userScrollDirection); + position?.applyFullDragUpdate(innerDelta); + } + } else { + updateUserScrollDirection(position, userScrollDirection); + final double? outerDelta = position?.applyClampedDragUpdate(delta); + if (outerDelta != 0.0 && outerDelta != null) { + updateUserScrollDirection(_pageScrollPosition, userScrollDirection); + _pageScrollPosition.applyFullDragUpdate(outerDelta); + } + } + } + + bool applyContentDimensions(double minScrollExtent, double maxScrollExtent, ShopScrollPosition position) { + if (pinnedHeaderSliverHeightBuilder != null) { + maxScrollExtent = maxScrollExtent - pinnedHeaderSliverHeightBuilder!(); + maxScrollExtent = math.max(0.0, maxScrollExtent); + } + return position.applyContentDimensions(minScrollExtent, maxScrollExtent, true); + } + + /// 当默认位置不为0时,主部件已下拉距离超过默认位置,但超过的距离不大于该值时, + /// 若手指离开屏幕,主部件头部会回弹至默认位置 + final double _scrollRedundancy = 80; + + /// 当前页面Header最大程度展开状态 + PageExpandState pageExpand = PageExpandState.NotExpand; + set (PageExpandState value) { + pageExpand = value; + pageExpandChange?.call(); + } + + /// 当手指离开屏幕 + void onPointerUp(PointerUpEvent event) { + final double _pagePixels = _pageScrollPosition.pixels; + if (0.0 < _pagePixels && _pagePixels < (_pageInitialOffset ?? 0)) { + if (pageExpand == PageExpandState.NotExpand + && (_pageInitialOffset ?? 0) - _pagePixels > _scrollRedundancy && _pageScrollPosition.userScrollDirection == ScrollDirection.forward) { + _pageScrollPosition.animateTo( + 0.0, + duration: const Duration(milliseconds: 400), + curve: Curves.ease, + ).then((_) => set(PageExpandState.Expanded)); + } else if (pageExpand == PageExpandState.Expanded && _pageScrollPosition.userScrollDirection == ScrollDirection.reverse) { + pageExpand = PageExpandState.Expanding; + _pageScrollPosition.animateTo((_pageInitialOffset ?? 0), + duration: const Duration(milliseconds: 400), + curve: Curves.ease, + ).then((_) => set(PageExpandState.NotExpand)); + } + } + } + + Function()? pageExpandChange; + + /// 更新用户滑动方向 + void updateUserScrollDirection(ShopScrollPosition? position, ScrollDirection? value) { + assert(position != null && value != null); + position!.didUpdateScrollDirection(value!); + } + + /// 以特定的速度开始一个物理驱动的模拟,该模拟确定 [pixels] 位置。 + /// + /// 此方法遵从 [ScrollPhysics.createBallisticSimulation],通常在当前位置超出范围时 + /// 提供滑动模拟,而在当前位置超出范围但具有非零速度时提供摩擦模拟。 + /// + /// 速度应以 逻辑像素/秒 为单位。 + void goBallistic(double velocity) => _pageScrollPosition.goBallistic(velocity); +} diff --git a/lib/store/shop/shop_scroll_position.dart b/lib/store/shop/shop_scroll_position.dart new file mode 100644 index 00000000..3ba62ad6 --- /dev/null +++ b/lib/store/shop/shop_scroll_position.dart @@ -0,0 +1,315 @@ +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/physics.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +import 'shop_scroll_coordinator.dart'; + +/// 滑动位置信息 +class ShopScrollPosition extends ScrollPosition implements ScrollActivityDelegate { + ShopScrollPosition({ + required ScrollPhysics physics, + required ScrollContext context, + double initialPixels = 0.0, + bool keepScrollOffset = true, + ScrollPosition? oldPosition, + String? debugLabel, + required this.coordinator, + }) : super( + physics: physics, + context: context, + keepScrollOffset: keepScrollOffset, + oldPosition: oldPosition, + debugLabel: debugLabel, + ) { + // 如果oldPosition不为null,则父级将首先调用Absorb(),它可以设置_pixels和_activity. + correctPixels(initialPixels); + if (activity == null) { + goIdle(); + } + assert(activity != null); + } + + final ShopScrollCoordinator coordinator; // 协调器 + ScrollDragController? _currentDrag; + double _heldPreviousVelocity = 0.0; + + @override + AxisDirection get axisDirection => context.axisDirection; + + @override + double setPixels(double newPixels) { + assert(activity!.isScrolling); + return super.setPixels(newPixels); + } + + @override + void pointerScroll(double delta) { + // TODO: implement pointerScroll + } + + @override + void absorb(ScrollPosition other) { + super.absorb(other); + if (other is! ShopScrollPosition) { + goIdle(); + return; + } + activity!.updateDelegate(this); + final ShopScrollPosition typedOther = other as ShopScrollPosition; + _userScrollDirection = typedOther._userScrollDirection; + assert(_currentDrag == null); + if (typedOther._currentDrag != null) { + _currentDrag = typedOther._currentDrag; + _currentDrag!.updateDelegate(this); + typedOther._currentDrag = null; + } + } + + @override + void applyNewDimensions() { + super.applyNewDimensions(); + context.setCanDrag(physics.shouldAcceptUserOffset(this)); + } + + /// 返回未使用的增量。 + /// + /// 正增量表示下降(在上方显示内容),负增量向上(在下方显示内容)。 + double applyClampedDragUpdate(double delta) { + assert(delta != 0.0); + // 如果我们要朝向 maxScrollExtent(负滚动偏移),那么我们在 minScrollExtent 方向上 + // 可以达到的最大距离是负无穷大。例如,如果我们已经过度滚动,则滚动以减少过度滚动不应 + // 禁止过度滚动。如果我们要朝 minScrollExtent(正滚动偏移量)方向移动,那么我们在 + // minScrollExtent 方向上可以达到的最大距离是我们现在所处的位置。 + // 换句话说,我们不能通过 applyClampedDragUpdate 进入过滚动状态。 + // 尽管如此,可能通过多种方式进入了过度滚动的情况。一种是物理是否允许通过 + // applyFullDragUpdate(请参见下文)。 + // 可能会发生过度滚动的情况,例如,使用滚动控制器人工设置了滚动位置。 + final double min = + delta < 0.0 ? -double.infinity : math.min(minScrollExtent, pixels); + // max 的逻辑是等效的,但反向。 + final double max = + delta > 0.0 ? double.infinity : math.max(maxScrollExtent, pixels); + final double oldPixels = pixels; + final double newPixels = (pixels - delta).clamp(min, max) as double; + final double clampedDelta = newPixels - pixels; + if (clampedDelta == 0.0) { + return delta; + } + final double overScroll = physics.applyBoundaryConditions(this, newPixels); + final double actualNewPixels = newPixels - overScroll; + final double offset = actualNewPixels - oldPixels; + if (offset != 0.0) { + forcePixels(actualNewPixels); + didUpdateScrollPositionBy(offset); + } + return delta + offset; + } + + // 返回过度滚动。 + double applyFullDragUpdate(double delta) { + assert(delta != 0.0); + final double oldPixels = pixels; + // Apply friction: 施加摩擦: + final double newPixels = + pixels - physics.applyPhysicsToUserOffset(this, delta); + if (oldPixels == newPixels) { + // 增量一定很小,我们在添加浮点数时将其删除了 + return 0.0; + } + // Check for overScroll: 检查过度滚动: + final double overScroll = physics.applyBoundaryConditions(this, newPixels); + final double actualNewPixels = newPixels - overScroll; + if (actualNewPixels != oldPixels) { + forcePixels(actualNewPixels); + didUpdateScrollPositionBy(actualNewPixels - oldPixels); + } + return overScroll; + } + + /// 当手指滑动时,该方法会获取到滑动距离。 + /// + /// [delta] 滑动距离,正增量表示下滑,负增量向上滑。 + /// + /// 我们需要把子部件的滑动数据交给协调器处理,主部件无干扰。 + @override + void applyUserOffset(double delta) { + final ScrollDirection userScrollDirection = + delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse; + if (debugLabel != coordinator.pageLabel) { + return coordinator.applyUserOffset(delta, userScrollDirection, this); + } + updateUserScrollDirection(userScrollDirection); + setPixels(pixels - physics.applyPhysicsToUserOffset(this, delta)); + } + + @override + void beginActivity(ScrollActivity? newActivity) { + _heldPreviousVelocity = 0.0; + if (newActivity == null) { + return; + } + assert(newActivity.delegate == this); + super.beginActivity(newActivity); + _currentDrag?.dispose(); + _currentDrag = null; + if (!activity!.isScrolling) { + updateUserScrollDirection(ScrollDirection.idle); + } + } + + /// 将用户滚动方向设置为给定值。 + /// 如果更改了该值,则将分派 [User ScrollNotification]。 + @protected + @visibleForTesting + void updateUserScrollDirection(ScrollDirection value) { + assert(value != null); + if (userScrollDirection == value) { + return; + } + _userScrollDirection = value; + didUpdateScrollDirection(value); + } + + @override + ScrollHoldController hold(VoidCallback holdCancelCallback) { + final double previousVelocity = activity!.velocity; + final HoldScrollActivity holdActivity = HoldScrollActivity( + delegate: this, + onHoldCanceled: holdCancelCallback, + ); + beginActivity(holdActivity); + _heldPreviousVelocity = previousVelocity; + return holdActivity; + } + + @override + Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) { + final ScrollDragController drag = ScrollDragController( + delegate: this, + details: details, + onDragCanceled: dragCancelCallback, + carriedVelocity: physics.carriedMomentum(_heldPreviousVelocity), + motionStartDistanceThreshold: physics.dragStartDistanceMotionThreshold, + ); + beginActivity(DragScrollActivity(this, drag)); + assert(_currentDrag == null); + _currentDrag = drag; + return drag; + } + + @override + void goIdle() { + beginActivity(IdleScrollActivity(this)); + } + + /// 以特定的速度开始一个物理驱动的模拟,该模拟确定 [pixels] 位置。 + /// 此方法遵从 [ScrollPhysics.createBallisticSimulation],该方法通常在当前位置超出 + /// 范围时提供滑动模拟,而在当前位置超出范围但具有非零速度时提供摩擦模拟。 + /// 速度应以逻辑像素/秒为单位。 + @override + void goBallistic(double velocity, [bool fromCoordinator = false]) { + if (debugLabel != coordinator.pageLabel) { + if (velocity > 0.0) { + coordinator.goBallistic(velocity); + } + } else { + if (fromCoordinator && velocity <= 0.0) { + return; + } + if (coordinator.pageExpand == PageExpandState.Expanding) { + return; + } + } + final Simulation? simulation = physics.createBallisticSimulation(this, velocity); + if (simulation != null) { + beginActivity(BallisticScrollActivity(this, simulation, context.vsync, true)); + } else { + goIdle(); + } + } + + @override + bool applyContentDimensions(double minScrollExtent, double maxScrollExtent, + [bool fromCoordinator = false]) { + if (debugLabel == coordinator.pageLabel && !fromCoordinator) + return coordinator.applyContentDimensions( + minScrollExtent, maxScrollExtent, this); + return super.applyContentDimensions(minScrollExtent, maxScrollExtent); + } + + @override + ScrollDirection get userScrollDirection => _userScrollDirection; + ScrollDirection _userScrollDirection = ScrollDirection.idle; + + @override + Future animateTo( + double to, { + required Duration duration, + required Curve curve, + }) { + if (nearEqual(to, pixels, physics.tolerance.distance)) { + // 跳过动画,直接移到我们已经靠近的位置。 + jumpTo(to); + return Future.value(); + } + + final DrivenScrollActivity activity = DrivenScrollActivity( + this, + from: pixels, + to: to, + duration: duration, + curve: curve, + vsync: context.vsync, + ); + beginActivity(activity); + return activity.done; + } + + @override + void jumpTo(double value) { + goIdle(); + if (pixels != value) { + final double oldPixels = pixels; + forcePixels(value); + notifyListeners(); + didStartScroll(); + didUpdateScrollPositionBy(pixels - oldPixels); + didEndScroll(); + } + goBallistic(0.0); + } + + @Deprecated('This will lead to bugs.') + @override + void jumpToWithoutSettling(double value) { + goIdle(); + if (pixels != value) { + final double oldPixels = pixels; + forcePixels(value); + notifyListeners(); + didStartScroll(); + didUpdateScrollPositionBy(pixels - oldPixels); + didEndScroll(); + } + } + + @override + void dispose() { + _currentDrag?.dispose(); + _currentDrag = null; + super.dispose(); + } + + @override + void debugFillDescription(List description) { + super.debugFillDescription(description); + description.add('${context.runtimeType}'); + description.add('$physics'); + description.add('$activity'); + description.add('$userScrollDirection'); + } + +} diff --git a/lib/store/shop_details_page.dart b/lib/store/shop_details_page.dart index 7af8a8c6..33029976 100644 --- a/lib/store/shop_details_page.dart +++ b/lib/store/shop_details_page.dart @@ -18,6 +18,7 @@ import 'package:huixiang/store/store_view/people_num.dart'; import 'package:huixiang/store/store_view/shop_car.dart'; import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; @@ -99,20 +100,17 @@ class _ShopDetailsPage extends State { SmartDialog.showLoading( msg: S.current.zhengzaijiazai, ); - SharedPreferences value = await SharedPreferences.getInstance(); - if (apiService == null) - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - BaseData? baseData = - await apiService?.queryStoreInfo(storeId).catchError((error) { + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + BaseData? baseData = await apiService?.queryStoreInfo(storeId).catchError((error) { debugPrint("${error}"); - return Future.value(null); + return BaseData()..isSuccess = false; }); - if (baseData?.isSuccess ?? false) { - storeInfo = StoreInfo.fromJson(baseData!.data); + if ((baseData?.isSuccess ?? false) && baseData!.data != null) { + storeInfo = baseData.data; activitys = storeInfo?.informationVOPageVO?.list ?.map((e) => Activity.fromJson(e)) .toList(); @@ -128,20 +126,16 @@ class _ShopDetailsPage extends State { minLogin() async { apiService?.minLogin(storeId).catchError((onError) { debugPrint("${onError}"); - return Future.value(null); + return BaseData()..isSuccess = false; }).then((BaseData? baseData) { if (baseData?.isSuccess ?? false) { Map minStoreInfo = baseData!.data; String minToken = minStoreInfo["token"]; String? tenant = storeInfo?.tenantCode; String? storeId = storeInfo?.id; - SharedPreferences.getInstance().then( - (value) => { - value.setString('minToken', minToken), - value.setString('tenant', tenant ?? ""), - value.setString('storeId', storeId ?? ""), - }, - ); + + SharedInstance.instance.saveMini(minToken, tenant, storeId); + minService = MinApiService( Dio(), context: context, @@ -161,10 +155,9 @@ class _ShopDetailsPage extends State { ///商品详情 queryMiNiDetail(id) async { - BaseData? baseData = - await minService?.miNiDetail(id).catchError((error) { + BaseData? baseData = await minService?.miNiDetail(id).catchError((error) { refreshController.refreshFailed(); - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { @@ -188,10 +181,9 @@ class _ShopDetailsPage extends State { ///获取父订单(火锅订单加菜前调用) getParentInfo() async { - BaseData? baseData = - await minService?.getParentInfo("$tableId").catchError((error) { + BaseData? baseData = await minService?.getParentInfo("$tableId").catchError((error) { debugPrint("${error}"); - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (baseData!.data != null) { @@ -231,7 +223,7 @@ class _ShopDetailsPage extends State { "tableId": tableId, }).catchError((error) { debugPrint("${error}"); - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { StoreInfo storeInfo = StoreInfo.fromJson(baseData!.data); @@ -321,8 +313,7 @@ class _ShopDetailsPage extends State { ///清空购物车 clearShopCar() async { - BaseData? baseData = - await minService?.clearShoppingCart(num.parse(storeId)); + BaseData? baseData = await minService?.clearShoppingCart(num.parse(storeId)); if (baseData?.isSuccess ?? false) { shopCarGoods = null; setState(() {}); @@ -409,7 +400,7 @@ class _ShopDetailsPage extends State { "tableId": tableId, }, ], - }).catchError(() { + }).catchError((error) { return BaseListData()..isSuccess = false; }); SmartDialog.dismiss(); @@ -420,8 +411,6 @@ class _ShopDetailsPage extends State { toDownOrder(); setState(() {}); }); - } else { - SmartDialog.showToast(baseDate?.msg ?? "", alignment: Alignment.center); } } @@ -431,10 +420,8 @@ class _ShopDetailsPage extends State { pid = ""; //活动 cName = ""; //优惠券 cid = ""; //优惠券 - BaseListData? baseDate = - await minService?.getShoppingCart(tableId); - if ((baseDate?.isSuccess ?? false) && - (baseDate!.data?.isNotEmpty ?? false)) { + BaseListData? baseDate = await minService?.getShoppingCart(tableId); + if ((baseDate?.isSuccess ?? false) && (baseDate!.data?.isNotEmpty ?? false)) { if (baseDate.data![0].selectDiscount == 1) { baseDate.data![0].couponList?.forEach((element) { if (element.isMaxCoupon ?? false) { @@ -493,8 +480,7 @@ class _ShopDetailsPage extends State { ///商品➕1 add(MiniDetail miNiDetail, selectSkus) async { - ProductSkuVOList? productSku = - miNiDetail.productSkuVOList?.firstWhere((element) { + ProductSkuVOList? productSku = miNiDetail.productSkuVOList?.firstWhere((element) { return skuY(element, selectSkus); }); String? skuId = productSku?.id; @@ -505,8 +491,7 @@ class _ShopDetailsPage extends State { shopCarGoods?.tableId = "$tableId"; if (shopSkuIndex >= 0) { - int buyNum = - shopCarGoods?.shoppingCartSkuItemList?[shopSkuIndex].buyNum ?? 0; + int buyNum = shopCarGoods?.shoppingCartSkuItemList?[shopSkuIndex].buyNum ?? 0; shopCarGoods?.shoppingCartSkuItemList?[shopSkuIndex].buyNum = buyNum + 1; SkuItemList? cartSkuItem = shopCarGoods?.shoppingCartSkuItemList ?.firstWhere((element) => skuId == element.id); @@ -516,8 +501,7 @@ class _ShopDetailsPage extends State { return; } - BaseListData? baseDate = - await minService?.shoppingCartSingle(shopCarTemp); + BaseListData? baseDate = await minService?.shoppingCartSingle(shopCarTemp); if (baseDate?.isSuccess ?? false) { queryShopCar().then((value) { this.shopCarGoods = value; @@ -528,20 +512,17 @@ class _ShopDetailsPage extends State { ///商品➖1 reduce(MiniDetail miNiDetail, selectSkus) async { - ProductSkuVOList? productSku = - miNiDetail.productSkuVOList?.firstWhere((element) { + ProductSkuVOList? productSku = miNiDetail.productSkuVOList?.firstWhere((element) { return skuY(element, selectSkus); }); String? skuId = productSku?.id; SkuItemList? shopSkuItem = shopCarGoods?.shoppingCartSkuItemList ?.firstWhere((element) => skuId == element.id); int shopSkuIndex = shopCarGoods?.shoppingCartSkuItemList - ?.indexWhere((element) => skuId == element.id) ?? - -1; + ?.indexWhere((element) => skuId == element.id) ?? -1; if ((shopSkuItem?.buyNum ?? 0) > 1) { - int buyNum = - shopCarGoods?.shoppingCartSkuItemList?[shopSkuIndex].buyNum ?? 0; + int buyNum = shopCarGoods?.shoppingCartSkuItemList?[shopSkuIndex].buyNum ?? 0; shopCarGoods?.shoppingCartSkuItemList?[shopSkuIndex].buyNum = buyNum - 1; } shopCarGoods?.tableId = "$tableId"; @@ -551,8 +532,7 @@ class _ShopDetailsPage extends State { ?.firstWhere((element) => skuId == element.id); shopCarTemp["shoppingCartSkuItemList"] = [cartSkuItem?.toJson()]; - BaseListData? baseDate = - await minService?.shoppingCartSingle(shopCarTemp); + BaseListData? baseDate = await minService?.shoppingCartSingle(shopCarTemp); if (baseDate?.isSuccess ?? false) { queryShopCar().then((value) { this.shopCarGoods = value; @@ -585,8 +565,7 @@ class _ShopDetailsPage extends State { selectedPrice = productSku?.skuPrice ?? ""; String? skuId = productSku?.id; int shopSkuIndex = shopCarGoods?.shoppingCartSkuItemList - ?.indexWhere((element) => skuId == element.id) ?? - -1; + ?.indexWhere((element) => skuId == element.id) ?? -1; if (shopSkuIndex >= 0) { counts = shopCarGoods?.shoppingCartSkuItemList?[shopSkuIndex].buyNum ?? 0; } @@ -655,7 +634,7 @@ class _ShopDetailsPage extends State { ), ], ), - ) + ), ], ), ), @@ -689,7 +668,8 @@ class _ShopDetailsPage extends State { style: TextStyle( fontSize: 12.sp, color: Color(0xFFFFFFFF), - fontWeight: MyFontWeight.bold), + fontWeight: MyFontWeight.bold, + ), ), TextSpan( text: "${shopCarGoods?.cartSum ?? 0}", @@ -700,7 +680,8 @@ class _ShopDetailsPage extends State { fontWeight: MyFontWeight.medium, ), ), - ]), + ], + ), ), Spacer(), GestureDetector( @@ -774,7 +755,7 @@ class _ShopDetailsPage extends State { offset: Offset(0, 3), blurRadius: 14, spreadRadius: 0, - ) + ), ], color: Color(0xFFFFFFFF), ), @@ -832,7 +813,8 @@ class _ShopDetailsPage extends State { "id": id, "storeId": storeId, "tableId": tableId - }); + }, + ); queryShopCar().then((value) { this.shopCarGoods = value; setState(() {}); @@ -961,10 +943,13 @@ class _ShopDetailsPage extends State { selectSpecsShowBottomSheet() { showModalBottomSheet( builder: (BuildContext context) { - return StatefulBuilder(builder: (context, state) { + return StatefulBuilder( + builder: (context, state) { return Container( alignment: Alignment.topCenter, - padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 16), + padding: EdgeInsets.symmetric( + horizontal: 14.w, vertical: 16, + ), height: MediaQuery.of(context).size.height / 3 * 2, width: double.infinity, decoration: BoxDecoration( @@ -1004,8 +989,7 @@ class _ShopDetailsPage extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, + mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( @@ -1159,10 +1143,12 @@ class _ShopDetailsPage extends State { ], ), ); - }); + }, + ); }, backgroundColor: Colors.transparent, - context: context); + context: context, + ); } Widget attrItem(Function fc, AttrList attrListBean, position) { @@ -1203,7 +1189,8 @@ class _ShopDetailsPage extends State { tag.attrValue, (selectSkus.length > position && tag.attrValue == selectSkus[position]), - )); + ), + ); }).toList()); } @@ -1229,7 +1216,8 @@ class _ShopDetailsPage extends State { fontSize: 14.sp, fontWeight: MyFontWeight.regular, ), - )); + ), + ); } ///扫码提示弹窗 @@ -1298,7 +1286,7 @@ class _ShopDetailsPage extends State { flex: 1, ), ], - ) + ), ], ), ), diff --git a/lib/store/shopping/activity_prefecture_details.dart b/lib/store/shopping/activity_prefecture_details.dart index 7d0eca2e..d384ff0a 100644 --- a/lib/store/shopping/activity_prefecture_details.dart +++ b/lib/store/shopping/activity_prefecture_details.dart @@ -13,10 +13,10 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; class ActivityPrefectureDetails extends StatefulWidget { final Map? arguments; @@ -85,36 +85,28 @@ class _ActivityPrefectureDetails extends State { storeId = widget.arguments?["storeId"] ?? ""; tenant = widget.arguments?["tenant"] ?? ""; - SharedPreferences.getInstance().then((value) { - minLogin(value); - queryStoreInfo(); - }); + minLogin(); + queryStoreInfo(); } /// 小程序登录 - minLogin(SharedPreferences shared) async { + minLogin() async { SmartDialog.showLoading( msg: S.of(context).zhengzaijiazai, ); apiService = ApiService( Dio(), context: context, - token: shared.getString('token') ?? "", + token: SharedInstance.instance.token, showLoading: false, ); apiService?.minLogin(storeId).catchError((onError) { - debugPrint(onError.toString()); + return BaseData()..isSuccess = false; }).then((baseData) { - if (baseData?.isSuccess ?? false) { + if (baseData.isSuccess ?? false) { minToken = baseData.data["token"]; queryStoreInfo(); - SharedPreferences.getInstance().then( - (value) => { - value.setString('minToken', minToken), - value.setString('tenant', tenant), - value.setString('storeId', storeId), - }, - ); + SharedInstance.instance.saveMini(minToken, tenant, storeId); minService = MinApiService( Dio(), context: context, @@ -124,7 +116,6 @@ class _ActivityPrefectureDetails extends State { showLoading: false, ); queryFindActListByType(pageType == "2" ? false : true); - SmartDialog.dismiss(); } }); @@ -132,12 +123,12 @@ class _ActivityPrefectureDetails extends State { /// 查询店铺信息 queryStoreInfo() async { - BaseData? baseData = + BaseData? baseData = await apiService?.queryStoreInfo(storeId).catchError((error) { - debugPrint(error.toString()); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { - storeInfo = StoreInfo.fromJson(baseData!.data); + storeInfo = baseData!.data; activitys = storeInfo?.informationVOPageVO?.list ?.map((e) => Activity.fromJson(e)) .toList(); @@ -154,6 +145,7 @@ class _ActivityPrefectureDetails extends State { ?.findActListByType(allDay, pageType) .catchError((error) { refreshController.refreshFailed(); + return BaseData()..isSuccess = false; }); setState(() { actTimeList.clear(); @@ -284,7 +276,7 @@ class _ActivityPrefectureDetails extends State { child: ListView.builder( scrollDirection: Axis.horizontal, physics: BouncingScrollPhysics(), - itemCount: actTimeList.length ?? 0, + itemCount: actTimeList.length, itemBuilder: (context, position) { return GestureDetector( onTap: () { @@ -629,7 +621,7 @@ class _ActivityPrefectureDetails extends State { ) : ListView.builder( padding: EdgeInsets.zero, - itemCount: productList.length ?? 0, + itemCount: productList.length, scrollDirection: Axis.vertical, shrinkWrap: true, physics: _scrollPhysics, diff --git a/lib/store/shopping/shopping_goods_details.dart b/lib/store/shopping/shopping_goods_details.dart index 1680c751..3620c2c0 100644 --- a/lib/store/shopping/shopping_goods_details.dart +++ b/lib/store/shopping/shopping_goods_details.dart @@ -22,11 +22,11 @@ import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/settlement/settlement_model.dart'; import 'package:huixiang/store/store_view/product_sku.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_footer.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; class ShoppingGoodsDetails extends StatefulWidget { @@ -104,44 +104,35 @@ class _ShoppingGoodsDetails extends State { bannerImg = widget.arguments?["bannerImg"]; productId = widget.arguments?["productId"]; if (pageType == "1") startCountdownTimer(); - debugPrint("store_param tenant:$tenant storeId:$storeId"); - SharedPreferences.getInstance().then((value) { - minLogin(value); - queryStoreInfo(); - }); + minLogin(); + queryStoreInfo(); } /// 小程序登录 - minLogin(SharedPreferences shared) async { + minLogin() async { SmartDialog.showLoading( msg: S.of(context).zhengzaijiazai, ); apiService = ApiService( Dio(), context: context, - token: shared.getString('token') ?? "", + token: SharedInstance.instance.token, showLoading: false, ); - apiService?.minLogin(storeId ?? "").catchError((onError) { - debugPrint(onError.toString()); + apiService?.minLogin(storeId).catchError((onError) { + return BaseData()..isSuccess = false; }).then((baseData) { - if (baseData?.isSuccess ?? false) { + if (baseData.isSuccess ?? false) { minToken = baseData.data["token"] ?? ""; queryStoreInfo(); - SharedPreferences.getInstance().then( - (value) => { - value.setString('minToken', minToken), - value.setString('tenant', tenant ?? ""), - value.setString('storeId', storeId ?? ""), - }, - ); + SharedInstance.instance.saveMini(minToken, tenant, storeId); minService = MinApiService( Dio(), context: context, - token: minToken ?? "", - tenant: tenant ?? "", - storeId: storeId ?? "", + token: minToken, + tenant: tenant, + storeId: storeId, showLoading: false, ); queryMemberInfo(); @@ -154,25 +145,20 @@ class _ShoppingGoodsDetails extends State { ///会员信息 queryMemberInfo() async { BaseData? baseData = await minService?.memberInfo().catchError((error) { - debugPrint("${error}"); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { - SharedPreferences.getInstance().then( - (value) => { - value.setString('minMember', jsonEncode(baseData!.data)), - }, - ); + SharedInstance.instance.saveMiniMember(jsonEncode(baseData!.data)); } } /// 查询店铺信息 queryStoreInfo() async { - BaseData? baseData = - await apiService?.queryStoreInfo(storeId).catchError((error) { - debugPrint(error.toString()); + BaseData? baseData = await apiService?.queryStoreInfo(storeId).catchError((error) { + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { - storeInfo = StoreInfo.fromJson(baseData!.data); + storeInfo = baseData!.data; activitys = storeInfo?.informationVOPageVO?.list ?.map((e) => Activity.fromJson(e)) .toList(); @@ -185,9 +171,9 @@ class _ShoppingGoodsDetails extends State { ///商品详情 queryMiNiDetail(id) async { - BaseData? baseData = - await minService?.miNiDetail(id).catchError((error) { + BaseData? baseData = await minService?.miNiDetail(id).catchError((error) { refreshController.refreshFailed(); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { @@ -202,10 +188,10 @@ class _ShoppingGoodsDetails extends State { ///活动商品详情 queryViewProduct(actProductId, pageType) async { - BaseData? baseData = await minService - ?.viewProduct(actProductId, pageType) + BaseData? baseData = await minService?.viewProduct(actProductId, pageType) .catchError((error) { refreshController.refreshFailed(); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { @@ -316,7 +302,7 @@ class _ShoppingGoodsDetails extends State { "tableId": tableId, }, ], - }).catchError(() => BaseListData()..isSuccess = false); + }).catchError((error) => BaseListData()..isSuccess = false); SmartDialog.dismiss(); if (baseDate?.isSuccess ?? false) { SmartDialog.showToast("添加购物车成功", alignment: Alignment.center); @@ -1165,7 +1151,7 @@ class _ShoppingGoodsDetails extends State { color: Color(0xFFFFFFFF), ), child: Text( - "${limitNumber ?? 0}人团", + "${limitNumber}人团", style: TextStyle( fontSize: 9.sp, fontWeight: MyFontWeight.semi_bold, diff --git a/lib/store/shopping/shopping_home/bargain_details.dart b/lib/store/shopping/shopping_home/bargain_details.dart index 4ca23648..12f0e5f8 100644 --- a/lib/store/shopping/shopping_home/bargain_details.dart +++ b/lib/store/shopping/shopping_home/bargain_details.dart @@ -9,6 +9,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/store_info.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; @@ -60,19 +61,18 @@ class _BargainDetails extends State { storeInfo = widget.arguments?["storeInfo"]; // skuId = widget.arguments["skuId"]; startCountdownTimer(); - SharedPreferences.getInstance().then((value) { - String minToken = value.getString("minToken") ?? ""; - String tenant = value.getString("tenant") ?? ""; - String storeId = value.getString("storeId") ?? ""; - minService = MinApiService( - Dio(), - context: context, - token: minToken, - tenant: tenant, - storeId: storeId, - ); - queryShowOneAct(actRecordId); - }); + + String minToken = SharedInstance.instance.miniToken; + String tenant = SharedInstance.instance.tenant; + String storeId = SharedInstance.instance.storeId; + minService = MinApiService( + Dio(), + context: context, + token: minToken, + tenant: tenant, + storeId: storeId, + ); + queryShowOneAct(actRecordId); } ///团购/秒杀时间 diff --git a/lib/store/shopping/shopping_home/group_details.dart b/lib/store/shopping/shopping_home/group_details.dart index fa3747f4..8ed20a48 100644 --- a/lib/store/shopping/shopping_home/group_details.dart +++ b/lib/store/shopping/shopping_home/group_details.dart @@ -8,12 +8,12 @@ import 'package:huixiang/data/activity_act_record_details.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; -import 'package:shared_preferences/shared_preferences.dart'; class GroupDetails extends StatefulWidget { final Map? arguments; @@ -51,19 +51,18 @@ class _GroupDetails extends State { super.initState(); actRecordId = widget.arguments?["actRecordId"]; startCountdownTimer(); - SharedPreferences.getInstance().then((value) { - String minToken = value.getString("minToken") ?? ""; - String tenant = value.getString("tenant") ?? ""; - String storeId = value.getString("storeId") ?? ""; - minService = MinApiService( - Dio(), - context: context, - token: minToken, - tenant: tenant, - storeId: storeId, - ); - queryShowOneAct(actRecordId); - }); + + String minToken = SharedInstance.instance.miniToken; + String tenant = SharedInstance.instance.tenant; + String storeId = SharedInstance.instance.storeId; + minService = MinApiService( + Dio(), + context: context, + token: minToken, + tenant: tenant, + storeId: storeId, + ); + queryShowOneAct(actRecordId); } final SwiperController controller = SwiperController(); @@ -96,6 +95,7 @@ class _GroupDetails extends State { queryShowOneAct(actRecordId) async { BaseData? baseData = await minService?.showOneAct(actRecordId).catchError((error) { refreshController.refreshFailed(); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { diff --git a/lib/store/shopping/shopping_home/search_page.dart b/lib/store/shopping/shopping_home/search_page.dart index b77880cb..325598c9 100644 --- a/lib/store/shopping/shopping_home/search_page.dart +++ b/lib/store/shopping/shopping_home/search_page.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:get/get.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/base_list_data.dart'; import 'package:huixiang/data/find_mini_group.dart'; @@ -7,6 +8,7 @@ import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/view_widget/custom_image.dart'; @@ -91,38 +93,29 @@ class _SearchPage extends State ///获取保存列表 getHistorySearch() async { - SharedPreferences value = await SharedPreferences.getInstance(); - var str = value.getString("historySearch"); - if (str == null) return; - var strArr = str.split("&"); - strArr.removeAt(strArr.length - 1); - setState(() { - historySearch.clear(); - historySearch.addAll(strArr.reversed); - }); + if (SharedInstance.instance.searchHistory.isNotEmpty) { + setState(() { + historySearch.clear(); + historySearch.addAll(SharedInstance.instance.searchHistory); + }); + } } ///保存列表 setHistorySearch(String text) async { if (text.trim() == "") return; - SharedPreferences value = await SharedPreferences.getInstance(); - var str = value.getString("historySearch"); - if (str == null) str = ""; - var strArr = str.split("&"); - if (strArr.length > 60) { - str = strArr.getRange(0, 59).join("&"); - } else { - str = strArr.join("&"); + List history = SharedInstance.instance.searchHistory; + if (history.any((element) => text == element)) { + history.remove(text); + history.insert(0, text); } - str += text + "&"; - value.setString("historySearch", str); + SharedInstance.instance.saveSearchHistory(history); getHistorySearch(); } ///删除历史列表 delHistorySearch() async { - SharedPreferences value = await SharedPreferences.getInstance(); - value.setString("historySearch", ""); + SharedInstance.instance.saveSearchHistory([]); getHistorySearch(); } diff --git a/lib/store/shopping/shopping_home/shopping_home_page.dart b/lib/store/shopping/shopping_home/shopping_home_page.dart index ea27c04a..a00c632a 100644 --- a/lib/store/shopping/shopping_home/shopping_home_page.dart +++ b/lib/store/shopping/shopping_home/shopping_home_page.dart @@ -50,18 +50,16 @@ class _ShoppingHomePage extends State @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - minService = MinApiService( - Dio(), - context: context, - token: widget.minToken ?? "", - tenant: widget.tenant, - storeId: widget.storeId, - showLoading: false, - ); - queryHomeConfig(); - queryRecommendList(); - }); + minService = MinApiService( + Dio(), + context: context, + token: widget.minToken ?? "", + tenant: widget.tenant, + storeId: widget.storeId, + showLoading: false, + ); + queryHomeConfig(); + queryRecommendList(); } @override diff --git a/lib/store/shopping/shopping_mall_home.dart b/lib/store/shopping/shopping_mall_home.dart index 8f3ca5e5..fb356a68 100644 --- a/lib/store/shopping/shopping_mall_home.dart +++ b/lib/store/shopping/shopping_mall_home.dart @@ -11,6 +11,7 @@ import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/store/shopping/shopping_cart/shopping_cart_page.dart'; import 'package:huixiang/store/shopping/shopping_home/shopping_home_page.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; class ShoppingMallHome extends StatefulWidget { @@ -46,38 +47,31 @@ class _ShoppingMallHome extends State debugPrint("store_param tenant:$tenant storeId:$storeId"); - SharedPreferences.getInstance().then((value) { - minLogin(value); - queryStoreInfo(); - }); + minLogin(); + queryStoreInfo(); } /// 小程序登录 - minLogin(SharedPreferences shared) async { + minLogin() async { SmartDialog.showLoading( msg: S.of(context).zhengzaijiazai, ); apiService = ApiService( Dio(), context: context, - token: shared.getString('token') ?? "", + token: SharedInstance.instance.token, showLoading: false, ); apiService?.minLogin(storeId).catchError((onError) { debugPrint(onError.toString()); + return BaseData()..isSuccess = false; }).then((baseData) { - if (baseData?.isSuccess ?? false) { + if (baseData.isSuccess ?? false) { setState(() { minToken = baseData.data["token"]; }); queryStoreInfo(); - SharedPreferences.getInstance().then( - (value) => { - value.setString('minToken', minToken ?? ""), - value.setString('tenant', tenant), - value.setString('storeId', storeId), - }, - ); + SharedInstance.instance.saveMini(minToken, tenant, storeId); minService = MinApiService( Dio(), context: context, @@ -94,12 +88,12 @@ class _ShoppingMallHome extends State /// 查询店铺信息 queryStoreInfo() async { - BaseData? baseData = - await apiService?.queryStoreInfo(storeId).catchError((error) { + BaseData? baseData = await apiService?.queryStoreInfo(storeId).catchError((error) { debugPrint(error.toString()); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { - storeInfo = StoreInfo.fromJson(baseData!.data); + storeInfo = baseData!.data; activitys = storeInfo?.informationVOPageVO?.list ?.map((e) => Activity.fromJson(e)) .toList(); @@ -125,12 +119,13 @@ class _ShoppingMallHome extends State height: 230.h, decoration: BoxDecoration( gradient: new LinearGradient( - begin: Alignment.centerRight, - end: Alignment.centerLeft, - colors: [ - Color(0xFFE8F5E9), - Color(0xFFE5F7FF), - ]), + begin: Alignment.centerRight, + end: Alignment.centerLeft, + colors: [ + Color(0xFFE8F5E9), + Color(0xFFE5F7FF), + ], + ), ), ), if (choiceIndex == 0) @@ -160,62 +155,64 @@ class _ShoppingMallHome extends State children: [ Expanded( child: GestureDetector( - onTap: () { - setState(() { - choiceIndex = 0; - }); - }, - child: Column( - children: [ - Image.asset( - choiceIndex == 0 - ? "assets/image/shopping_home.webp" - : "assets/image/shopping_home_h.webp", - width: 30, - height: 30, - ), - Text( - "首页", - style: TextStyle( - fontSize: 10.sp, - fontWeight: MyFontWeight.semi_bold, - color: choiceIndex == 0 - ? Color(0xFF4C4C4C) - : Color(0xFFC6C6C6), - ), + onTap: () { + setState(() { + choiceIndex = 0; + }); + }, + child: Column( + children: [ + Image.asset( + choiceIndex == 0 + ? "assets/image/shopping_home.webp" + : "assets/image/shopping_home_h.webp", + width: 30, + height: 30, + ), + Text( + "首页", + style: TextStyle( + fontSize: 10.sp, + fontWeight: MyFontWeight.semi_bold, + color: choiceIndex == 0 + ? Color(0xFF4C4C4C) + : Color(0xFFC6C6C6), ), - ], - )), + ), + ], + ), + ), ), Expanded( - child: GestureDetector( - onTap: () { - setState(() { - choiceIndex = 1; - }); - }, - child: Column( - children: [ - Image.asset( - choiceIndex == 0 - ? "assets/image/shopping_cart_h.webp" - : "assets/image/shopping_cart.webp", - width: 30, - height: 30, - ), - Text( - "购物车", - style: TextStyle( - fontSize: 10.sp, - fontWeight: MyFontWeight.semi_bold, - color: choiceIndex == 0 - ? Color(0xFFC6C6C6) - : Color(0xFF4C4C4C), + child: GestureDetector( + onTap: () { + setState(() { + choiceIndex = 1; + }); + }, + child: Column( + children: [ + Image.asset( + choiceIndex == 0 + ? "assets/image/shopping_cart_h.webp" + : "assets/image/shopping_cart.webp", + width: 30, + height: 30, ), - ), - ], + Text( + "购物车", + style: TextStyle( + fontSize: 10.sp, + fontWeight: MyFontWeight.semi_bold, + color: choiceIndex == 0 + ? Color(0xFFC6C6C6) + : Color(0xFF4C4C4C), + ), + ), + ], + ), ), - )) + ), ], ), ), diff --git a/lib/store/store_order.dart b/lib/store/store_order.dart index 7310258f..c00005e3 100644 --- a/lib/store/store_order.dart +++ b/lib/store/store_order.dart @@ -1,8 +1,7 @@ import 'dart:convert'; +import 'dart:math'; import 'package:dio/dio.dart'; -import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -19,6 +18,8 @@ import 'package:huixiang/data/store_info.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/store/shop/shop_scroll_controller.dart'; +import 'package:huixiang/store/shop/shop_scroll_coordinator.dart'; import 'package:huixiang/store/store_view/people_num.dart'; import 'package:huixiang/store/store_view/product_sku.dart'; import 'package:huixiang/store/store_view/shop_car.dart'; @@ -27,12 +28,13 @@ import 'package:huixiang/store/store_view/store_order_list.dart'; import 'package:huixiang/utils/constant.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/receive_success.dart'; import 'package:huixiang/view_widget/round_button.dart'; import 'package:intl/intl.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; + class StoreOrderPage extends StatefulWidget { final Map? arguments; @@ -55,7 +57,6 @@ class _StoreOrderPage extends State StoreOrderListPage? storeOrderListPage; ScrollPhysics scrollPhysics = NeverScrollableScrollPhysics(); - ScrollController controller = ScrollController(); ShoppingCart? shopCarGoods; int tableId = 0; String parentId = ""; @@ -67,9 +68,6 @@ class _StoreOrderPage extends State MemberVo? memberVo; MiniDetail? miniDetail; - GlobalKey nestedScrollViewKey = - GlobalKey(); - ///小程序token String? minToken; String? pName; @@ -80,6 +78,7 @@ class _StoreOrderPage extends State @override void initState() { super.initState(); + _shopCoordinator = ShopScrollCoordinator(); tableId = widget.arguments?["tableId"] ?? 0; tenant = widget.arguments?["tenant"]; @@ -87,33 +86,24 @@ class _StoreOrderPage extends State tabcontroller = TabController(length: 1, vsync: this); - debugPrint( - "store_param tableId:$tableId tenant:$tenant storeId:$storeId"); + _pageScrollController = _shopCoordinator.pageScrollController(0); - SharedPreferences.getInstance().then((value) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString('token') ?? "", - ); - minLogin(value); - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); + minLogin(); } /// 小程序登录 - minLogin(SharedPreferences shared) async { - SmartDialog.showLoading( - msg: S.of(context).zhengzaijiazai, - ); + minLogin() async { + // SmartDialog.showLoading( + // msg: S.of(context).zhengzaijiazai, + // ); minToken = widget.arguments?["miniToken"]; await queryStoreInfo(); - SharedPreferences.getInstance().then( - (value) => { - value.setString('minToken', minToken ?? ""), - value.setString('tenant', tenant), - value.setString('storeId', storeId), - }, - ); + SharedInstance.instance.saveMini(minToken, tenant, storeId); minService = MinApiService( Dio(), context: context, @@ -137,31 +127,25 @@ class _StoreOrderPage extends State queryMemberInfo() async { BaseData? baseData = await minService?.memberInfo().catchError((error) { debugPrint("${error}"); - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { - SharedPreferences.getInstance().then( - (value) => { - value.setString('minMember', jsonEncode(baseData!.data)), - }, - ); - memberVo = MemberVo.fromJson(baseData!.data); + SharedInstance.instance.saveMiniMember(jsonEncode(baseData!.data)); + memberVo = MemberVo.fromJson(baseData.data); } } ///获取父订单(火锅订单加菜前调用) getParentInfo() async { - BaseData? baseData = - await minService?.getParentInfo("$tableId").catchError((error) { + BaseData? baseData = await minService?.getParentInfo("$tableId").catchError((error) { debugPrint("${error}"); - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (baseData?.data != null) { parentId = baseData!.data["id"]; parentCode = baseData.data["parentCode"]; } else { - ///TODO: 没有父订单, queryStoreInfo1(); } } @@ -169,16 +153,16 @@ class _StoreOrderPage extends State ///获取桌子信息 queryStoreInfo1() async { - BaseData? baseData = await minService?.queryStoreInfo1({ + BaseData? baseData = await minService?.queryStoreInfo1({ "getCoupon": true, "storeId": storeId, "tableId": tableId, }).catchError((error) { debugPrint("${error}"); - return Future.value(null); + return BaseData()..isSuccess = false; }); - if (baseData?.isSuccess ?? false) { - StoreInfo storeInfo = StoreInfo.fromJson(baseData!.data); + if ((baseData?.isSuccess ?? false) && baseData?.data != null) { + StoreInfo storeInfo = baseData!.data!; showPeopleNum(storeInfo.storeTable?.tableName); } } @@ -204,6 +188,12 @@ class _StoreOrderPage extends State RefreshController? refreshController; bool dialogShowing = false; + final ScrollController controller1 = ScrollController(); + final ScrollController controller2 = ScrollController(); + + late ShopScrollCoordinator _shopCoordinator; + ShopScrollController? _pageScrollController; + @override Widget build(BuildContext context) { return PopScope( @@ -212,7 +202,7 @@ class _StoreOrderPage extends State SmartDialog.dismiss(); } }, - canPop: false, + canPop: true, child: Container( color: Colors.white, child: Stack( @@ -222,46 +212,28 @@ class _StoreOrderPage extends State right: 0, top: 0, bottom: 54.h, - child: ExtendedNestedScrollView( - controller: controller, - key: nestedScrollViewKey, - dragStartBehavior: DragStartBehavior.start, - scrollBehavior: ScrollBehavior(), - floatHeaderSlivers: true, - physics: ClampingScrollPhysics(), - headerSliverBuilder: (BuildContext context, bool innerScrolled) { - return [ + child: Listener( + onPointerUp: _shopCoordinator.onPointerUp, + child: CustomScrollView( + controller: _pageScrollController, + physics: ClampingScrollPhysics(), + slivers: [ SliverAppBar( - expandedHeight: - (storeInfo?.couponVOList?.isNotEmpty ?? true) - ? 440.h - : 395.h, + expandedHeight: 400, pinned: true, + collapsedHeight: kToolbarHeight, systemOverlayStyle: SystemUiOverlayStyle.dark, + surfaceTintColor: Colors.white, + backgroundColor: Colors.white, flexibleSpace: FlexibleSpaceBar( title: Title( - controller, + _pageScrollController!, storeInfo?.storeName ?? '', - (alpha) { - // setState(() { - // if (alpha == 1) - // scrollPhysics = BouncingScrollPhysics(); - // else - // scrollPhysics = - // NeverScrollableScrollPhysics(); - // }); - }, ), centerTitle: false, titlePadding: EdgeInsets.symmetric( - vertical: 16, + vertical: 10, ), - collapseMode: CollapseMode.pin, - stretchModes: [ - StretchMode.zoomBackground, - // StretchMode.fadeTitle, - StretchMode.blurBackground, - ], background: Container( child: Stack( children: [ @@ -272,10 +244,6 @@ class _StoreOrderPage extends State Spacer(), ], ), - top: 0, - bottom: 0, - left: 0, - right: 0, ), Positioned( top: 0, @@ -308,8 +276,7 @@ class _StoreOrderPage extends State widget.arguments?["distance"], ), ), - top: 233.h, - bottom: 38.h, + top: 233, left: 0, right: 0, ), @@ -335,85 +302,103 @@ class _StoreOrderPage extends State ), ), ), - backgroundColor: Colors.white, centerTitle: false, - elevation: 0, leadingWidth: 0, automaticallyImplyLeading: false, - bottom: PreferredSize( - preferredSize: Size( - Get.width, - 38.h, - ), + ), + SliverPersistentHeader( + pinned: true, + floating: false, + delegate: _SliverAppBarDelegate( + maxHeight: 50, + minHeight: 50, child: Container( width: Get.width, - child: Theme( - data: ThemeData( - splashColor: Colors.transparent, - // 点击时的水波纹颜色设置为透明 - highlightColor: - Colors.transparent, // 点击时的背景高亮颜色设置为透明 + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(8), + topRight: Radius.circular(8), ), - child: Row( - children: [ - 20.vd, - Column( - children: [ - Text( - // Color(0xFF32A060), - S.of(context).diandan, - style: TextStyle( - color: Colors.black, - fontSize: 18.sp, - fontWeight: FontWeight.bold, - ), + ), + child: Row( + children: [ + 20.vd, + Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + // Color(0xFF32A060), + S.of(context).diandan, + style: TextStyle( + color: Colors.black, + fontSize: 18.sp, + fontWeight: FontWeight.bold, ), - 5.d, - Container( - width: 20, - height: 3, - decoration: BoxDecoration( - borderRadius: - BorderRadius.circular(2), - color: Color(0xFF32A060), - ), + ), + 5.d, + Container( + width: 20, + height: 3, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(2), + color: Color(0xFF32A060), ), - 10.d, - ], - ), - Spacer(), - ], - ), + ), + 10.d, + ], + ), + Spacer(), + ], ), ), ), ), - ]; - }, - pinnedHeaderSliverHeightBuilder: () { - final double statusBarHeight = - MediaQuery.of(context).padding.top; - return statusBarHeight + kToolbarHeight + 38.h; - }, - body: StoreOrderListPage( - widget.arguments, - activitys, - storeInfo, - shopCarGoods, - controller1, - controller2, - nestedScrollViewKey, - minToken, - tenant, - tableId, - _queryMiNiDetail, - () { - queryShopCar().then((value) { - this.shopCarGoods = value; - setState(() {}); - }); - }, - scrollPhysics, + SliverFillRemaining( + child: StoreOrderListPage( + widget.arguments, + activitys, + storeInfo, + shopCarGoods, + _shopCoordinator, + minToken, + tenant, + tableId, + _queryMiNiDetail, + () { + queryShopCar().then((value) { + this.shopCarGoods = value; + setState(() {}); + }); + }, + scrollPhysics, + ), + ), + ], + // pinnedHeaderSliverHeightBuilder: () { + // final double statusBarHeight = MediaQuery.of(context).padding.top; + // return statusBarHeight + kToolbarHeight + 38; + // }, + // body: StoreOrderListPage( + // widget.arguments, + // activitys, + // storeInfo, + // shopCarGoods, + // controller1, + // controller2, + // nestedScrollViewKey, + // minToken, + // tenant, + // tableId, + // _queryMiNiDetail, + // () { + // queryShopCar().then((value) { + // this.shopCarGoods = value; + // setState(() {}); + // }); + // }, + // scrollPhysics, + // ), ), ), ), @@ -805,7 +790,12 @@ class _StoreOrderPage extends State if (miniDetail?.subscribeParam?.isEnableSubscribe ?? false) toDownOrder(); setState(() {}); } else { - SmartDialog.showToast("${baseDate?.msg}", alignment: Alignment.center); + if (baseDate?.msg?.isNotEmpty ?? false) { + SmartDialog.showToast( + "${baseDate?.msg}", + alignment: Alignment.center, + ); + } } } @@ -819,8 +809,9 @@ class _StoreOrderPage extends State return null; } BaseListData? baseDate = - await minService?.getShoppingCart(tableId); - if ((baseDate?.isSuccess ?? false) && (baseDate!.data?.length ?? 0) > 0) { + await minService?.getShoppingCart(tableId).catchLEr(); + if ((baseDate?.isSuccess ?? false) && + (baseDate!.data?.isNotEmpty ?? false)) { if (baseDate.data![0].selectDiscount == 1) { baseDate.data![0].couponList?.forEach((element) { if (element.isMaxCoupon ?? false) { @@ -851,17 +842,13 @@ class _StoreOrderPage extends State await minService?.shoppingCartSingle(shopCarTemp); if (baseDate?.isSuccess ?? false) { this.shopCarGoods = await queryShopCar(); - if (shopCartKey != null) { - shopCartKey.currentState?.setState(() {}); - } + shopCartKey.currentState?.setState(() {}); } else { this.shopCarGoods = await queryShopCar(); - if (shopCartKey != null) { - shopCartKey.currentState?.setState(() {}); - } - if (baseDate != null && baseDate.msg != null && baseDate.msg != "") { + shopCartKey.currentState?.setState(() {}); + if (baseDate?.msg?.isNotEmpty ?? false) { SmartDialog.showToast( - "${baseDate.msg}", + "${baseDate!.msg}", alignment: Alignment.center, ); } @@ -971,19 +958,15 @@ class _StoreOrderPage extends State }); return gg; } - - final ScrollController controller1 = ScrollController(); - final ScrollController controller2 = ScrollController(); - Drag? _drag; - } class Title extends StatefulWidget { - final ScrollController controller; + final ShopScrollController controller; final String title; - final Function scrollChange; - Title(this.controller, this.title, this.scrollChange); + // final Function scrollChange; + + Title(this.controller, this.title /*, this.scrollChange*/); @override State createState() { @@ -999,22 +982,10 @@ class _Title extends State { super.initState(); widget.controller.addListener(() { double maxScrollExtent = widget.controller.position.maxScrollExtent; - double alphaHeight = kToolbarHeight + 38.h; - double alphaProgress = maxScrollExtent - widget.controller.offset; - // debugPrint("controller.offset: ${widget.controller.offset}"); - double alphaTemp = 0; - if (alphaProgress <= 1) { - alphaTemp = 1; - } else if (alphaProgress <= alphaHeight) { - alphaTemp = - (((alphaHeight - alphaProgress) / alphaHeight) > 0.5) ? 1 : 0; - } else { - alphaTemp = 0; - } - // debugPrint("alpha: $alpha"); + debugPrint(" maxScrollExtent: $maxScrollExtent offset: ${widget.controller.offset} s/m: ${(widget.controller.offset / maxScrollExtent)}"); + double alphaTemp = (widget.controller.offset / maxScrollExtent) > 0.70 ? 1 : 0; if (alpha != alphaTemp && mounted) { alpha = alphaTemp; - widget.scrollChange(alpha); setState(() {}); } }); @@ -1023,36 +994,71 @@ class _Title extends State<Title> { @override Widget build(BuildContext context) { return Container( - alignment: Alignment.centerLeft, - child: alpha == 0 - ? null - : Row( - children: [ - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - Navigator.of(context).pop(); - }, - child: Container( - margin: EdgeInsets.only(left: 10.w), - padding: EdgeInsets.all(10.h), - child: Icon( - Icons.arrow_back_ios, - color: Colors.black, - size: 24, - ), - ), + alignment: Alignment.bottomLeft, + height: kToolbarHeight, + child: alpha == 0 ? null : Container( + child: Row( + children: [ + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + Navigator.of(context).pop(); + }, + child: Container( + margin: EdgeInsets.only(left: 10.w), + padding: EdgeInsets.all(10.h), + child: Icon( + Icons.arrow_back_ios, + color: Colors.black, + size: 24, ), - Text( - widget.title ?? "", - style: TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: 18.sp, - ), + ), + ), + Expanded( + child: Text( + widget.title ?? "", + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 18.sp, ), - ], + ), ), + ], + ), + ) ); } } + + +class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { + _SliverAppBarDelegate({ + required this.minHeight, + required this.maxHeight, + required this.child, + }); + + final double minHeight; + final double maxHeight; + final Widget child; + + @override + double get minExtent => this.minHeight; + + @override + double get maxExtent => max(maxHeight, minHeight); + + @override + Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { + return SizedBox.expand(child: child); + } + + @override + bool shouldRebuild(_SliverAppBarDelegate oldDelegate) { + return maxHeight != oldDelegate.maxHeight || + minHeight != oldDelegate.minHeight || + child != oldDelegate.child; + } +} diff --git a/lib/store/store_view/product_meals_sku.dart b/lib/store/store_view/product_meals_sku.dart index 0173dd41..fcbb4a36 100644 --- a/lib/store/store_view/product_meals_sku.dart +++ b/lib/store/store_view/product_meals_sku.dart @@ -12,10 +12,10 @@ import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/round_button.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:shared_preferences/shared_preferences.dart'; class ProductMealsSku extends StatefulWidget { final arguments; @@ -48,25 +48,24 @@ class _ProductMealsSku extends State<ProductMealsSku> { tableId = widget.arguments["tableId"]; id = widget.arguments["id"]; storeId = widget.arguments["storeId"]; - SharedPreferences.getInstance().then((value) { - String minToken = value.getString("minToken") ?? ""; - String tenant = value.getString("tenant") ?? ""; - String storeId = value.getString("storeId") ?? ""; - minService = MinApiService(Dio(), - context: context, - token: minToken, - tenant: tenant, - storeId: storeId, - showLoading: true); - queryMiNiDetail(id); - }); + + String minToken = SharedInstance.instance.miniToken; + String tenant = SharedInstance.instance.tenant; + storeId = SharedInstance.instance.storeId; + minService = MinApiService(Dio(), + context: context, + token: minToken, + tenant: tenant, + storeId: storeId, + showLoading: true); + queryMiNiDetail(id); } ///商品详情 queryMiNiDetail(id) async { - BaseData<MiniDetail>? baseData = - await minService?.miNiDetail(id).catchError((error) { + BaseData<MiniDetail>? baseData = await minService?.miNiDetail(id).catchError((error) { refreshController.refreshFailed(); + return BaseData<MiniDetail>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { setState(() { @@ -120,7 +119,7 @@ class _ProductMealsSku extends State<ProductMealsSku> { BaseListData<ShoppingCart>? baseDate = await minService ?.addShoppingCart(requestData) - .catchError(() => BaseListData<ShoppingCart>()..isSuccess = false); + .catchError((error) => BaseListData<ShoppingCart>()..isSuccess = false); SmartDialog.dismiss(); if (baseDate?.isSuccess ?? false) { Navigator.of(context).pop(); diff --git a/lib/store/store_view/shop_goods.dart b/lib/store/store_view/shop_goods.dart index 9b12ff4c..fcc451c6 100644 --- a/lib/store/store_view/shop_goods.dart +++ b/lib/store/store_view/shop_goods.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/mini_detail.dart'; import 'package:huixiang/data/shopping_cart.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/utils/str_utils.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/round_button.dart'; @@ -57,24 +58,22 @@ class _ShopGoods extends State<ShopGoods> { ///商品详情 queryMiNiDetail(id) async { MinApiService? minService; - await SharedPreferences.getInstance().then((value) { - String minToken = value.getString("minToken") ?? ""; - String tenant = value.getString("tenant") ?? ""; - String storeId = value.getString("storeId") ?? ""; - minService = MinApiService( - Dio(), - context: context, - token: minToken, - tenant: tenant, - storeId: storeId, - ); + String minToken = SharedInstance.instance.miniToken; + String tenant = SharedInstance.instance.tenant; + String storeId = SharedInstance.instance.storeId; + minService = MinApiService( + Dio(), + context: context, + token: minToken, + tenant: tenant, + storeId: storeId, + ); + BaseData<MiniDetail>? baseData = await minService.miNiDetail(id).catchError((error) { + return BaseData<MiniDetail>()..isSuccess = false; }); - BaseData<MiniDetail>? baseData = - await minService?.miNiDetail(id).catchError((error) {}); - if (baseData?.isSuccess ?? false) { - miNiDetail = baseData!.data; - if (baseData.data?.productSkuVOList?[0].productSetMeals?.isEmpty ?? - true) { + if (baseData.isSuccess ?? false) { + miNiDetail = baseData.data; + if (baseData.data?.productSkuVOList?[0].productSetMeals?.isEmpty ?? true) { _jumpType = 0; if (widget.shoppingCartSkuItemListBean != null) { widget.add.call(widget.shoppingCartSkuItemListBean!); @@ -652,19 +651,17 @@ class _ShopGoods extends State<ShopGoods> { if ((tableId?.isNotEmpty ?? false) && (tenantCode?.isNotEmpty ?? false) && (shopId?.isNotEmpty ?? false)) { - await SharedPreferences.getInstance().then((value) { - String minToken = value.getString("minToken") ?? ""; - Navigator.of(context).pushNamed( - '/router/store_order', - arguments: { - "id": shopId, - "tenant": tenantCode, - "storeName": "", - "tableId": int.tryParse(tableId!), - "miniToken": minToken, - }, - ); - }); + String minToken = SharedInstance.instance.miniToken; + Navigator.of(context).pushNamed( + '/router/store_order', + arguments: { + "id": shopId, + "tenant": tenantCode, + "storeName": "", + "tableId": int.tryParse(tableId!), + "miniToken": minToken, + }, + ); } } else { await Permission.camera.request(); diff --git a/lib/store/store_view/store_info.dart b/lib/store/store_view/store_info.dart index e8246497..2b0f0ffa 100644 --- a/lib/store/store_view/store_info.dart +++ b/lib/store/store_view/store_info.dart @@ -30,25 +30,11 @@ class _StoreInfoView extends State<StoreInfoView> { @override Widget build(BuildContext context) { return Container( - margin: EdgeInsets.only( - // left: 16.w, - // right: 16.w, - // top: 5.h, - // bottom: 6.h, - ), height: MediaQuery.of(context).size.width >= 650 ? 180.h : 166.h, padding: EdgeInsets.all(12.w), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8.w), - // boxShadow: [ - // BoxShadow( - // color: Colors.black.withAlpha(25), - // offset: Offset(0, 3), - // blurRadius: 3, - // spreadRadius: 0, - // ), - // ], ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, diff --git a/lib/store/store_view/store_order_list.dart b/lib/store/store_view/store_order_list.dart index 8e4582c5..18c7ecc6 100644 --- a/lib/store/store_view/store_order_list.dart +++ b/lib/store/store_view/store_order_list.dart @@ -12,6 +12,8 @@ import 'package:huixiang/data/shopping_cart.dart'; import 'package:huixiang/data/store_info.dart'; import 'package:huixiang/retrofit/min_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/store/shop/shop_scroll_controller.dart'; +import 'package:huixiang/store/shop/shop_scroll_coordinator.dart'; import 'package:huixiang/store/store_view/shop_goods.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; @@ -22,15 +24,13 @@ class StoreOrderListPage extends StatefulWidget { final Map? arguments; final List<Activity>? activitys; final StoreInfo? storeInfo; - final ScrollController controller1; - final ScrollController controller2; + final ShopScrollCoordinator shopCoordinator; final String? minToken; final String tenant; final int tableId; final Function(String id, int count) queryMiNiDetail; final Function queryShoppingCart; final ScrollPhysics scrollPhysics; - final GlobalKey<ExtendedNestedScrollViewState> parentKey; ShoppingCart? shopCarGoods; StoreOrderListPage( @@ -38,9 +38,7 @@ class StoreOrderListPage extends StatefulWidget { this.activitys, this.storeInfo, this.shopCarGoods, - this.controller1, - this.controller2, - this.parentKey, + this.shopCoordinator, this.minToken, this.tenant, this.tableId, @@ -65,21 +63,41 @@ class _StoreOrderListPage extends State<StoreOrderListPage> { int currentIndex = 0; double _viewportDimension = 0; + late ShopScrollCoordinator _shopCoordinator; + late ShopScrollController _listScrollController1; + late ShopScrollController _listScrollController2; + @override void initState() { super.initState(); + _shopCoordinator = widget.shopCoordinator; + _listScrollController1 = _shopCoordinator.newChildScrollController(); + _listScrollController2 = _shopCoordinator.newChildScrollController(); + _listScrollController2.addListener(() { + _viewportDimension = _listScrollController2.position.viewportDimension; + for (int i = 0; i < (appletProducts?.length ?? 0); i++) { + if (currentIndex != i && _listScrollController2.offset >= (appletProducts?[i].goodsIndex ?? 0) && + (i == (appletProducts?.length ?? 0) - 1 || _listScrollController2.offset < (appletProducts?[i + 1].goodsIndex ?? 0))) { + setState(() { + currentIndex = i; + }); + break; + } + } + }); appletGoods(); } ///小程序查询分组及商品列表 appletGoods() async { - SharedPreferences value = await SharedPreferences.getInstance(); - minService = MinApiService(Dio(), - context: context, - token: widget.minToken ?? "", - tenant: widget.tenant, - storeId: widget.arguments?["id"], - showLoading: true); + minService = MinApiService( + Dio(), + context: context, + token: widget.minToken ?? "", + tenant: widget.tenant, + storeId: widget.arguments?["id"], + showLoading: true, + ); BaseListData<FindMiniGroup> baseData = await minService.findMiNiGroupList({ "id": widget.arguments?["id"], @@ -90,7 +108,7 @@ class _StoreOrderListPage extends State<StoreOrderListPage> { debugPrint("${error}"); return BaseListData<FindMiniGroup>()..isSuccess = false; }); - if (baseData?.isSuccess ?? false) { + if (baseData.isSuccess ?? false) { // refreshController.refreshCompleted(); setState(() { appletProducts = baseData.data ?? []; @@ -110,9 +128,6 @@ class _StoreOrderListPage extends State<StoreOrderListPage> { } } - Drag? drag; - ScrollPhysics scrollPhysics = NeverScrollableScrollPhysics(); - @override Widget build(BuildContext context) { return Container( @@ -126,59 +141,23 @@ class _StoreOrderListPage extends State<StoreOrderListPage> { width: 100, child: ListView.builder( itemCount: appletProducts?.length ?? 0, - physics: ClampingScrollPhysics(), - controller: widget.controller1, + physics: AlwaysScrollableScrollPhysics(), + controller: _listScrollController1, padding: EdgeInsets.only(top: 0, bottom: 12.h), itemBuilder: (context, position) { - return GestureDetector( - onTap: () {}, - child: orderItem(position), - ); + return orderItem(position); }, ), ), Expanded( - child: Listener( - onPointerMove: (event) { - double pixels = widget.parentKey.currentState?.outerController.position.pixels ?? 0; - double maxScrollExtent = widget.parentKey.currentState?.outerController.position.maxScrollExtent ?? 0; - if (event.delta.dy > 0) { - // 往下 - if (widget.controller2.position.pixels == 0) { - widget.parentKey.currentState?.outerController.jumpTo((widget.parentKey.currentState?.outerController.offset ?? 0) - (event.delta.dy)); - } - } else if (event.delta.dy < 0) { - // 往上 - if (pixels < maxScrollExtent) { - widget.parentKey.currentState?.outerController.jumpTo((widget.parentKey.currentState?.outerController.offset ?? 0) - (event.delta.dy)); - } - } - }, - onPointerUp: (event) { - debugPrint("onPointerUp-滚动: "); - double pixels = widget.parentKey.currentState?.outerController.position.pixels ?? 0; - double maxScrollExtent = widget.parentKey.currentState?.outerController.position.maxScrollExtent ?? 0; - debugPrint("onPointerUp-滚动: pixels: $pixels ; maxScrollExtent: $maxScrollExtent"); - if (pixels == 0) { - scrollPhysics = NeverScrollableScrollPhysics(); - setState(() {}); - } else if (pixels < maxScrollExtent) { - scrollPhysics = NeverScrollableScrollPhysics(); - setState(() {}); - } else if (!(scrollPhysics is ClampingScrollPhysics)) { - scrollPhysics = ClampingScrollPhysics(); - setState(() {}); - } + child: ListView.builder( + itemCount: appletProducts?.length ?? 0, + padding: EdgeInsets.only(top: 0), + controller: _listScrollController2, + physics: AlwaysScrollableScrollPhysics(), + itemBuilder: (context, position) { + return rightOrderItem(position); }, - child: ListView.builder( - itemCount: appletProducts?.length ?? 0, - padding: EdgeInsets.only(top: 0), - controller: widget.controller2, - physics: scrollPhysics, - itemBuilder: (context, position) { - return rightOrderItem(position); - }, - ), ), ), ], @@ -209,7 +188,7 @@ class _StoreOrderListPage extends State<StoreOrderListPage> { // productListBeans.clear(); // productListBeans.addAll(appletProducts[index].productList); int aindex = appletProducts![index].goodsIndex ?? 0; - widget.controller2.jumpTo(aindex.toDouble()); + _listScrollController2.jumpTo(aindex.toDouble()); }); }, child: Stack( @@ -356,4 +335,11 @@ class _StoreOrderListPage extends State<StoreOrderListPage> { ); } + @override + void dispose() { + _listScrollController1.dispose(); + _listScrollController2.dispose(); + super.dispose(); + } + } diff --git a/lib/union/union_details_page.dart b/lib/union/union_details_page.dart index 4d32e64d..7b7b1fec 100644 --- a/lib/union/union_details_page.dart +++ b/lib/union/union_details_page.dart @@ -13,6 +13,7 @@ import 'package:huixiang/union/union_view/store_info.dart'; import 'package:huixiang/union/union_view/union_coupon.dart'; import 'package:huixiang/union/union_view/vip.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/receive_success.dart'; @@ -43,10 +44,7 @@ class _UnionDetailsPage extends State<UnionDetailsPage> { List<Activity>? activitys; queryStoreInfo() async { - final SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService(Dio(), - context: context, token: value.getString('token') ?? ""); - + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token); BaseData? baseData = await apiService ?.queryStoreInfo(widget.arguments?["id"]) .catchError((error) { @@ -295,10 +293,7 @@ class _UnionDetailsPage extends State<UnionDetailsPage> { if (response.statusCode == 200) { downText = S.of(context).xiazaiwancheng; // SmartDialog.showProgress(progressValue, status: downText); - SharedPreferences.getInstance().then((value) { - value.setStringList( - "miniAppid", (value.getStringList("miniAppid") ?? [])..add(appId)); - }); + SharedInstance.instance.saveMiniAppId((SharedInstance.instance.miniAppids)..add(appId)); } else { print("print 下载失败"); } diff --git a/lib/union/union_list.dart b/lib/union/union_list.dart index fd6bab44..570a610b 100644 --- a/lib/union/union_list.dart +++ b/lib/union/union_list.dart @@ -8,6 +8,7 @@ import 'package:huixiang/data/store.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -52,14 +53,11 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { } queryStore() async { - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - ); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + ); BaseListData<Store>? baseData = await apiService?.queryStore({ "city": (widget.city ?? "") == "所有门店" ? "" : (widget.city ?? ""), // "district": district, @@ -70,8 +68,6 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { "serviceType": widget.serviceType, "exchange": false, }).catchError((error) { - SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type), - alignment: Alignment.center); networkStatus = -1; _refreshController.refreshFailed(); return BaseListData<Store>()..isSuccess = false; @@ -91,6 +87,7 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { @override Widget build(BuildContext context) { + super.build(context); return SmartRefresher( controller: _refreshController, enablePullDown: true, @@ -157,7 +154,9 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { Widget buildStoreItemSm() { return Container( margin: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 12.h), - padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h), + padding: EdgeInsets.symmetric( + horizontal: 12.w, vertical: 12.h, + ), width: double.infinity, decoration: BoxDecoration( color: Colors.white, @@ -169,7 +168,8 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { blurRadius: 12, spreadRadius: 0, ) - ]), + ], + ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -183,7 +183,9 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { ), ), Padding( - padding: EdgeInsets.only(left: 6.w, bottom: 5.h, top: 12.h), + padding: EdgeInsets.only( + left: 6.w, bottom: 5.h, top: 12.h, + ), child: Shimmer.fromColors( baseColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8), @@ -242,7 +244,7 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { offset: Offset(0, 1), blurRadius: 12, spreadRadius: 0, - ) + ), ], ), width: double.infinity, @@ -282,7 +284,7 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { fontWeight: MyFontWeight.regular, ), ), - ) + ), ], ), SizedBox( @@ -305,20 +307,18 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { SizedBox(height: 6.h), Row( children: [ - if (store.perCapitaConsumption != null && - (store.perCapitaConsumption ?? "") != "0") + if (store.perCapitaConsumption != null && (store.perCapitaConsumption ?? "") != "0") Padding( padding: EdgeInsets.only(right: 22.w), child: Text( - S.of(context).ren( - store.perCapitaConsumption ?? "", - ), + S.of(context).ren(store.perCapitaConsumption ?? ""), style: TextStyle( color: Color(0xFF4D4D4D), fontSize: 12.sp, fontWeight: MyFontWeight.regular, ), - )), + ), + ), Image.asset( "assets/image/icon_union_location_black.webp", fit: BoxFit.fill, @@ -328,11 +328,8 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { SizedBox(width: 4.w), Text( (store.distance ?? 0) > 1000 - ? S.of(context).gongli( - ((store.distance ?? 0) / 1000 * 100).toInt() / - 100.0) - : S.of(context).mi( - ((store.distance ?? 0) * 100).toInt() / 100.0), + ? S.of(context).gongli(((store.distance ?? 0) / 1000 * 100).toInt() / 100.0) + : S.of(context).mi(((store.distance ?? 0) * 100).toInt() / 100.0), style: TextStyle( color: Color(0xFF4D4D4D), fontSize: 12.sp, @@ -342,25 +339,22 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { ), SizedBox(height: 10.h), Row( - children: []..addAll(itemServer(store.businessService ?? "")), + children: itemServer(store.businessService ?? ""), ), SizedBox(height: store.businessService == "" ? 40.h : 23.h), Container( height: 105.h, child: ListView.builder( padding: EdgeInsets.zero, - itemCount: - (storeList![position].productShow?.length ?? 0) > 3 - ? 3 - : storeList![position].productShow?.length ?? 0, + itemCount: (storeList![position].productShow?.length ?? 0) > 3 + ? 3 : storeList![position].productShow?.length ?? 0, scrollDirection: Axis.horizontal, shrinkWrap: true, physics: BouncingScrollPhysics(), itemBuilder: (context, index) { return GestureDetector( onTap: () {}, - child: unionGoodsItem( - storeList![position].productShow![index]), + child: unionGoodsItem(storeList![position].productShow![index]), ); }, ), @@ -443,7 +437,8 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { blurRadius: 12, spreadRadius: 0, ) - ]), + ], + ), width: double.infinity, height: 235.h, child: Stack( @@ -525,9 +520,10 @@ class _UnionList extends State<UnionList> with AutomaticKeepAliveClientMixin { fontWeight: MyFontWeight.regular, ), ), - ) + ), ], - )), + ), + ), Container( width: 59.w, height: 18.h, diff --git a/lib/union/union_page.dart b/lib/union/union_page.dart index 47de16ed..84059a40 100644 --- a/lib/union/union_page.dart +++ b/lib/union/union_page.dart @@ -14,9 +14,9 @@ import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/union/union_list.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/location.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_tab.dart'; import 'package:permission_handler/permission_handler.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:visibility_detector/visibility_detector.dart'; import '../data/address.dart'; @@ -168,31 +168,30 @@ class UnionPageState extends State<UnionPage> } } - saveLatLng(Position latLng, province, city, district) async { - SharedPreferences prefs = await SharedPreferences.getInstance(); - await prefs.setString("latitude", "${latLng.latitude}"); - await prefs.setString("longitude", "${latLng.longitude}"); - if (province != null) await prefs.setString("province", province); - if (city != null) await prefs.setString("city", city); - if (district != null) await prefs.setString("district", district); + saveLatLng(Position latLng, String? province, String? city, String? district) async { + SharedInstance.instance.saveLatLng(latLng); + if (province?.isNotEmpty ?? false) SharedInstance.instance.setProvince(province); + if (city?.isNotEmpty ?? false) SharedInstance.instance.setProvince(city); + if (district?.isNotEmpty ?? false) SharedInstance.instance.setProvince(district); } getLatLng() async { - var tempLatLng = await SharedPreferences.getInstance(); - if (tempLatLng.containsKey("latitude") && - tempLatLng.containsKey("longitude") && - tempLatLng.containsKey("province") && - tempLatLng.containsKey("city") && - tempLatLng.containsKey("district")) { + + if (SharedInstance.instance.language.isNotEmpty && + SharedInstance.instance.longitude.isNotEmpty && + SharedInstance.instance.province.isNotEmpty && + SharedInstance.instance.city.isNotEmpty && + SharedInstance.instance.district.isNotEmpty) { latLng = Position( - latitude: double.tryParse(tempLatLng.getString("latitude") ?? "")!, - longitude: double.tryParse(tempLatLng.getString("longitude") ?? "")!, + latitude: double.tryParse(SharedInstance.instance.language)!, + longitude: double.tryParse(SharedInstance.instance.longitude)!, timestamp: DateTime.now(), accuracy: 0, altitude: 0, heading: 0, speed: 0, - speedAccuracy: 0); + speedAccuracy: 0, + ); } } diff --git a/lib/utils/app_util.dart b/lib/utils/app_util.dart index 0f7a6912..5ec8739e 100644 --- a/lib/utils/app_util.dart +++ b/lib/utils/app_util.dart @@ -1,14 +1,16 @@ - - - +import 'dart:ui' as ui; +import 'dart:async'; +import 'package:color_thief_dart/color_thief_dart.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; + import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; +import 'package:huixiang/utils/shared_preference.dart'; miniLogin(ApiService apiService, String storeId, Function(String token) callback) async { apiService.minLogin(storeId).then((baseData) async { - if (baseData?.isSuccess ?? false) { + if (baseData.isSuccess ?? false) { callback.call(baseData.data["token"]); } }, onError: (error) { @@ -29,3 +31,23 @@ miniLogin(ApiService apiService, String storeId, Function(String token) callback } +Future<Color?> loadShopColor(String imageUrl) async { + int? color = SharedInstance.instance.getShopColor(imageUrl); + if (color != null) { + return Color(color); + } + NetworkImage imageProvider = NetworkImage(imageUrl); + final completer = Completer<ui.Image>(); + imageProvider.resolve(ImageConfiguration.empty).addListener(ImageStreamListener((ImageInfo imageInfo, bool synchronousCall) { + completer.complete(imageInfo.image); + })); + final ui.Image loadedImage = await completer.future; + List<int>? colorRgb = await getColorFromImage(loadedImage); + if (colorRgb?.isNotEmpty ?? false) { + Color color = Color.fromARGB(255, colorRgb![0], colorRgb[1], colorRgb[2]); + SharedInstance.instance.saveShopColor(imageUrl, color.value); + return color; + } + return null; +} + diff --git a/lib/utils/shared_preference.dart b/lib/utils/shared_preference.dart new file mode 100644 index 00000000..0a1d80b6 --- /dev/null +++ b/lib/utils/shared_preference.dart @@ -0,0 +1,157 @@ + +import 'dart:convert'; + +import 'package:geolocator/geolocator.dart'; +import 'package:huixiang/data/user_entity.dart'; +import 'package:huixiang/data/user_info.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class SharedInstance { + + factory SharedInstance() => SharedInstance._internal(); + // instance的getter方法,singletonManager.instance获取对象 + static SharedInstance get instance => _getInstance(); + + // 静态变量_instance,存储唯一对象 + static SharedInstance? _instance; + + // 获取对象 + static SharedInstance _getInstance() { + _instance ??= SharedInstance._internal(); + return _instance!; + } + + SharedInstance._internal(); + + SharedPreferences? _storage; + + Future<void> init(SharedPreferences sharedPreferences) async { + _storage = sharedPreferences; + } + + void saveUser(UserInfo user) { + _storage?.setString('user', jsonEncode(user)); + } + + void saveUserInfo(UserEntity userEntity) { + _storage?.setString('userJson', jsonEncode(userEntity.toJson())); + _storage?.setString('token', "${userEntity.token}"); + _storage?.setString('userId', "${userEntity.userId}"); + _storage?.setString('nick', "${userEntity.name}"); + _storage?.setString('mobile', "${userEntity.mobile}"); + } + + void showPrivacyPolicy() { + _storage?.setBool('isShowPrivacyPolicy', true); + } + + void savePushData({String? pushData}) { + _storage?.setString('pushData', pushData ?? ""); + } + + void saveLatLng(Position? latLng) { + _storage?.setString("latitude", "${latLng?.latitude}"); + _storage?.setString("longitude", "${latLng?.longitude}"); + } + + void setProvince(province) { + _storage?.setString('province', province); + } + + void setCity(city) { + _storage?.setString('city', city); + } + + void setFirst() { + _storage?.setBool('isFirst', false); + } + + void setDistrict(district) { + _storage?.setString('district', district); + } + + void saveMini(minToken, tenant, storeId) { + _storage?.setString('minToken', minToken); + _storage?.setString('tenant', tenant); + _storage?.setString('storeId', storeId); + } + + void saveSearchHistory(List<String> history) { + _storage?.setStringList('historySearch', history); + } + + void saveMiniAppId(List<String> miniAppids) { + _storage?.setStringList('miniAppids', miniAppids); + } + + void saveAppLastVersion(String appLastVersion) { + _storage?.setString('appLastVersion', appLastVersion); + } + + String? getSize(String imageLocalPath) { + return _storage?.getString(imageLocalPath); + } + + void setSize(String imageLocalPath, String sizeMap) { + _storage?.setString(imageLocalPath, sizeMap); + } + + void saveToday(int today) { + _storage?.setInt('today', today); + } + + void saveActivityPosCode(String activityPosCode) { + _storage?.setString('ActivityPosCode', activityPosCode); + } + + void saveLanguage(String longitude) { + _storage?.setString('longitude', longitude); + } + + void saveMiniMember(String minMember) { + _storage?.setString('minMember', minMember); + } + + void logout() { + _storage?.setString("token", ""); + _storage?.setString("user", ""); + _storage?.setString("userJson", ""); + _storage?.setString("userId", ""); + _storage?.setString("mobile", ""); + _storage?.setString("nick", ""); + _storage?.setString("account", ""); + _storage?.setString("password", ""); + } + + String? get appLastVersion => _storage?.getString('appLastVersion'); + int? get today => _storage?.getInt('today'); + String get ActivityPosCode => _storage?.getString('ActivityPosCode') ?? ""; + String get latitude => _storage?.getString('latitude') ?? ""; + List<String> get searchHistory => _storage?.getStringList('historySearch') ?? []; + List<String> get miniAppids => _storage?.getStringList('miniAppids') ?? []; + String get minMember => _storage?.getString('minMember') ?? ""; + String get mobile => _storage?.getString('mobile') ?? ""; + String get province => _storage?.getString('province') ?? ""; + String get city => _storage?.getString('city') ?? ""; + String get district => _storage?.getString('district') ?? ""; + String get miniToken => _storage?.getString('miniToken') ?? ""; + String get storeId => _storage?.getString('storeId') ?? ""; + String get tenant => _storage?.getString('tenant') ?? ""; + String get userJson => _storage?.getString('user') ?? ""; + String get longitude => _storage?.getString('longitude') ?? ""; + String get userId => _storage?.getString('userId') ?? ""; + String get pushData => _storage?.getString('pushData') ?? ""; + String get token => _storage?.getString('token') ?? ""; + String get language => _storage?.getString('language') ?? ""; + bool get isShowPrivacyPolicy => _storage?.getBool('isShowPrivacyPolicy') ?? false; + bool get isFirst => _storage?.getBool('isFirst') ?? true; + + int? getShopColor(String shopLogo) { + return _storage?.getInt(shopLogo); + } + + void saveShopColor(String shopLogo, int value) { + _storage?.setInt(shopLogo, value); + } + +} \ No newline at end of file diff --git a/lib/utils/upload_async.dart b/lib/utils/upload_async.dart index 56d47f6a..718cba15 100644 --- a/lib/utils/upload_async.dart +++ b/lib/utils/upload_async.dart @@ -6,6 +6,7 @@ import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/upload_result.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:image_gallery_saver/image_gallery_saver.dart'; import 'package:image_pickers/image_pickers.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -80,10 +81,10 @@ class UploadAsync { }, maskWidget: SizedBox(), ); - var sp = await SharedPreferences.getInstance(); + ApiService apiService = ApiService( Dio(), - token: sp.getString("token"), + token: SharedInstance.instance.token, showLoading: false, ); diff --git a/lib/view_widget/hot_item.dart b/lib/view_widget/hot_item.dart index 7e308e66..d5cf6c5e 100644 --- a/lib/view_widget/hot_item.dart +++ b/lib/view_widget/hot_item.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/icon_text.dart'; import 'package:huixiang/view_widget/round_button.dart'; @@ -30,9 +31,7 @@ class _HotArticleItem extends State<HotArticleItem> { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), context: context, token: value.getString("token") ?? ""), - }); + apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token ?? ""); } ///关注/取关会员 @@ -72,92 +71,16 @@ class _HotArticleItem extends State<HotArticleItem> { offset: Offset(0, 3), blurRadius: 14, spreadRadius: 0, - ) + ), ], borderRadius: BorderRadius.circular(4), ), child: (!widget.isHot) ? Column( children: [ - // Row( - // mainAxisAlignment: MainAxisAlignment.spaceBetween, - // crossAxisAlignment: CrossAxisAlignment.center, - // children: [ - // Container( - // margin: EdgeInsets.only(left: 5), - // child: Row( - // children: [ - // MImage( - // (widget.article != null && - // widget.article.author != null) - // ? widget.article.author.avatar - // : "", - // width: 44, - // height: 44, - // isCircle: true, - // fit: BoxFit.cover, - // errorSrc: "assets/image/default_1.webp", - // fadeSrc: "assets/image/default_1.webp", - // ), - // SizedBox( - // width: 8, - // ), - // Column( - // mainAxisAlignment: MainAxisAlignment.spaceEvenly, - // crossAxisAlignment: CrossAxisAlignment.start, - // children: [ - // Text( - // (widget.article != null && - // widget.article.author != null) - // ? widget.article.author.name - // : "", - // style: TextStyle( - // fontSize: 14.sp, - // fontWeight: MyFontWeight.medium, - // color: Color(0xFF1A1A1A), - // ), - // ), - // Text( - // widget.article != null - // ? (widget.article.createTime.split(" ")[0]) - // : "", - // style: TextStyle( - // fontSize: 12.sp, - // fontWeight: MyFontWeight.regular, - // color: Color(0xFF808080), - // ), - // ), - // ], - // ), - // ], - // ), - // ), - // GestureDetector( - // onTap: (){ - // setState(() { - // widget.article.isFollow = !(widget.article.isFollow??false); - // _vipFollow(widget.article.updateUser); - // }); - // }, - // child: RoundButton( - // padding: EdgeInsets.symmetric( - // horizontal: 8, - // vertical: 3, - // ), - // backgroup: (widget.article.isFollow??false) ? Color(0xFFE6E6E6) : Color(0xFF32A060), - // textColor: (widget.article.isFollow??false) ? Color(0xFF808080):Colors.white , - // text:(widget.article.isFollow??false) ? "已关注":"关注", - // radius: 20, - // icons: Icon( - // (widget.article.isFollow??false) ? Icons.check: Icons.add, - // color:(widget.article.isFollow??false) ? Color(0xFF808080):Colors.white , - // size: 14, - // ), - // ), - // ), - // ], - // ), - Expanded(child:Row( + + Expanded( + child:Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox(height: 5.h), @@ -189,10 +112,9 @@ class _HotArticleItem extends State<HotArticleItem> { ], ), ),), - SizedBox(width:5.w,), ], - )), + ),), SizedBox(height: 10.h,) ], ) @@ -295,9 +217,7 @@ class _HotArticleItem extends State<HotArticleItem> { height: 16.h, ), Text( - (widget.article != null) - ? "${widget.article.viewers}" - : "", + "${widget.article.viewers ?? ""}", style: TextStyle( fontSize: 12.sp, color: Color(0xFF1A1A1A), @@ -319,9 +239,7 @@ class _HotArticleItem extends State<HotArticleItem> { height: 16.h, ), Text( - (widget.article != null) - ? "${widget.article.comments}" - : "", + "${widget.article.comments ?? ''}", style: TextStyle( fontSize: 12.sp, color: Color(0xFF1A1A1A), @@ -343,9 +261,7 @@ class _HotArticleItem extends State<HotArticleItem> { height: 16.h, ), Text( - (widget.article != null) - ? "${widget.article.likes}" - : "", + "${widget.article.likes ?? ''}", style: TextStyle( fontSize: 12.sp, color: Color(0xFF1A1A1A), @@ -368,7 +284,6 @@ class _HotArticleItem extends State<HotArticleItem> { fontWeight: MyFontWeight.regular, color: Color(0xFFB2B2B2), ), - // leftIcon: Icons.access_time_rounded, iconSize: 10, iconColor: Color(0xFFB2B2B2), ), diff --git a/lib/view_widget/icon_text.dart b/lib/view_widget/icon_text.dart index ff4b4f3a..33750c25 100644 --- a/lib/view_widget/icon_text.dart +++ b/lib/view_widget/icon_text.dart @@ -33,18 +33,31 @@ class IconText extends StatelessWidget { @override Widget build(BuildContext context) { var widgets = <Widget>[]; - if (leftIcon != null || (leftImage != "")) { - widgets.add( - Padding( - padding: EdgeInsets.only(left: 2.w), - child: Icon( - leftIcon, - size: iconSize, - color: iconColor, + if (leftIcon != null || (leftImage?.isNotEmpty ?? false)) { + if (leftIcon != null) { + widgets.add( + Padding( + padding: EdgeInsets.only(left: 2.w), + child: Icon( + leftIcon, + size: iconSize, + color: iconColor, + ), + ), + ); + } else { + widgets.add( + Padding( + padding: EdgeInsets.only(left: 2.w), + child: Image.asset( + leftImage!, + width: iconSize, + height: iconSize, + ), ), - ), - ); - } + ); + } + } widgets.add(SizedBox( width: space, @@ -72,22 +85,34 @@ class IconText extends StatelessWidget { width: space, )); - if (rightIcon != null || rightImage != "") { - widgets.add( - Padding( - padding: EdgeInsets.only(left: 2.w), - child: Icon( - rightIcon, - size: iconSize, - color: iconColor, + if (rightIcon != null || (rightImage?.isNotEmpty ?? false)) { + if (rightIcon != null) { + widgets.add( + Padding( + padding: EdgeInsets.only(left: 2.w), + child: Icon( + rightIcon, + size: iconSize, + color: iconColor, + ), + ), + ); + } else { + widgets.add( + Padding( + padding: EdgeInsets.only(left: 2.w), + child: Image.asset( + rightImage!, + width: iconSize, + height: iconSize, + ), ), - ), - ); - } + ); + } + } return Container( child: Row( - mainAxisAlignment: - isMax ? MainAxisAlignment.center : MainAxisAlignment.start, + mainAxisAlignment: isMax ? MainAxisAlignment.center : MainAxisAlignment.start, crossAxisAlignment: textAxisAlignment, mainAxisSize: MainAxisSize.min, children: widgets, diff --git a/lib/view_widget/login_tips_dialog.dart b/lib/view_widget/login_tips_dialog.dart index 198c6d04..5398306d 100644 --- a/lib/view_widget/login_tips_dialog.dart +++ b/lib/view_widget/login_tips_dialog.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'login_tips.dart'; @@ -30,14 +31,7 @@ class LoginTipsDialog { builder: (ctx) { return LoginTips( click: () { - SharedPreferences.getInstance().then((value) { - value.setString("token", ""); - value.setString("user", ""); - value.setString("userJson", ""); - value.setString("userId", ""); - value.setString("mobile", ""); - value.setString("nick", ""); - }); + SharedInstance.instance.logout(); Navigator.of(context).pushReplacementNamed( '/router/new_login_page', arguments: {"login": "login"}, diff --git a/lib/view_widget/mine_vip_entry.dart b/lib/view_widget/mine_vip_entry.dart index 2ac608b6..5f2a0277 100644 --- a/lib/view_widget/mine_vip_entry.dart +++ b/lib/view_widget/mine_vip_entry.dart @@ -5,6 +5,7 @@ import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/data/rank.dart'; import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -113,149 +114,149 @@ class MineVipEntry extends StatelessWidget { Widget widget = userInfo?.memberRankVo?.rankName != null ? Container( - height: 20.h, - width: double.infinity, - child: Row( - children: [ - Container( - height: double.infinity, - padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 4.h), - decoration: BoxDecoration( - color: logoColor, - borderRadius: BorderRadius.only( - topLeft: Radius.circular(4), - bottomLeft: Radius.circular(4), - ), - boxShadow: [ - BoxShadow( - color: Color(0x08213303).withAlpha(12), - offset: Offset(0, 2), - blurRadius: 4, - spreadRadius: 0, - ), - ], - ), - child: Image.asset( - "assets/image/mine_vip_logo.webp", - fit: BoxFit.cover, - // width: 13.w, - // height: 11.h, - ), - ), - Container( - height: double.infinity, - padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 3.h), - decoration: BoxDecoration( - color: levelTextBackdrop, - borderRadius: BorderRadius.only( - topRight: Radius.circular(4), - bottomRight: Radius.circular(4), - ), - boxShadow: [ - BoxShadow( - color: Color(0x08213303).withAlpha(12), - offset: Offset(0, 2), - blurRadius: 4, - spreadRadius: 0, - ), - ], - ), + height: 20.h, + width: double.infinity, child: Row( children: [ - Text( - levelText, - textAlign: TextAlign.center, - style: TextStyle( - color: levelTextColor, - fontSize: 10.sp, - fontWeight: MyFontWeight.regular, + Container( + height: double.infinity, + padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 4.h), + decoration: BoxDecoration( + color: logoColor, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(4), + bottomLeft: Radius.circular(4), + ), + boxShadow: [ + BoxShadow( + color: Color(0x08213303).withAlpha(12), + offset: Offset(0, 2), + blurRadius: 4, + spreadRadius: 0, + ), + ], + ), + child: Image.asset( + "assets/image/mine_vip_logo.webp", + fit: BoxFit.cover, + // width: 13.w, + // height: 11.h, ), ), - Image.asset( - "assets/image/icon_right.webp", - fit: BoxFit.cover, - width: 8, - height: 8, - color: levelTextColor, - ), + Container( + height: double.infinity, + padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 3.h), + decoration: BoxDecoration( + color: levelTextBackdrop, + borderRadius: BorderRadius.only( + topRight: Radius.circular(4), + bottomRight: Radius.circular(4), + ), + boxShadow: [ + BoxShadow( + color: Color(0x08213303).withAlpha(12), + offset: Offset(0, 2), + blurRadius: 4, + spreadRadius: 0, + ), + ], + ), + child: Row( + children: [ + Text( + levelText, + textAlign: TextAlign.center, + style: TextStyle( + color: levelTextColor, + fontSize: 10.sp, + fontWeight: MyFontWeight.regular, + ), + ), + Image.asset( + "assets/image/icon_right.webp", + fit: BoxFit.cover, + width: 8, + height: 8, + color: levelTextColor, + ), + ], + ), + ) ], ), ) - ], - ), - ) : Container( - height: 20.h, - width: double.infinity, - child: Row( - children: [ - Container( - height: double.infinity, - padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 4.h), - decoration: BoxDecoration( - color: Color(0xFFCACACA), - borderRadius: BorderRadius.only( - topLeft: Radius.circular(4), - bottomLeft: Radius.circular(4), - ), - boxShadow: [ - BoxShadow( - color: Color(0x08213303).withAlpha(12), - offset: Offset(0, 2), - blurRadius: 4, - spreadRadius: 0, - ), - ], - ), - child: Image.asset( - "assets/image/mine_vip_logo.webp", - fit: BoxFit.cover, - // width: 13.w, - // height: 11.h, - ), - ), - Container( - height: double.infinity, - padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 3.h), - decoration: BoxDecoration( - color: Color(0xFFFFF8EC), - borderRadius: BorderRadius.only( - topRight: Radius.circular(4), - bottomRight: Radius.circular(4), - ), - boxShadow: [ - BoxShadow( - color: Color(0x08213303).withAlpha(12), - offset: Offset(0, 2), - blurRadius: 4, - spreadRadius: 0, - ), - ], - ), + height: 20.h, + width: double.infinity, child: Row( children: [ - Text( - "开通会员", - textAlign: TextAlign.center, - style: TextStyle( + Container( + height: double.infinity, + padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 4.h), + decoration: BoxDecoration( color: Color(0xFFCACACA), - fontSize: 10.sp, - fontWeight: MyFontWeight.regular, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(4), + bottomLeft: Radius.circular(4), + ), + boxShadow: [ + BoxShadow( + color: Color(0x08213303).withAlpha(12), + offset: Offset(0, 2), + blurRadius: 4, + spreadRadius: 0, + ), + ], + ), + child: Image.asset( + "assets/image/mine_vip_logo.webp", + fit: BoxFit.cover, + // width: 13.w, + // height: 11.h, ), ), - Image.asset( - "assets/image/icon_right.webp", - fit: BoxFit.cover, - width: 8, - height: 8, - color: Color(0xFFCACACA), - ), + Container( + height: double.infinity, + padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 3.h), + decoration: BoxDecoration( + color: Color(0xFFFFF8EC), + borderRadius: BorderRadius.only( + topRight: Radius.circular(4), + bottomRight: Radius.circular(4), + ), + boxShadow: [ + BoxShadow( + color: Color(0x08213303).withAlpha(12), + offset: Offset(0, 2), + blurRadius: 4, + spreadRadius: 0, + ), + ], + ), + child: Row( + children: [ + Text( + "开通会员", + textAlign: TextAlign.center, + style: TextStyle( + color: Color(0xFFCACACA), + fontSize: 10.sp, + fontWeight: MyFontWeight.regular, + ), + ), + Image.asset( + "assets/image/icon_right.webp", + fit: BoxFit.cover, + width: 8, + height: 8, + color: Color(0xFFCACACA), + ), + ], + ), + ) ], ), - ) - ], - ), - ); + ); // Container( // width: double.infinity, // padding: EdgeInsets.only(top: 12.h, bottom: 22.h, left: 12.w, right: 12.w), @@ -348,25 +349,16 @@ class MineVipEntry extends StatelessWidget { return GestureDetector( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - // Navigator.of(context) - // .pushNamed('/router/mine_vip_level_page', arguments: { - // "rankLevel": curLevel, - // "createTime": (userInfo != null) ? "${userInfo.createTime}" : "", - // "points": (userInfo != null) ? int.tryParse(userInfo.points) : 0, - // }); - Navigator.of(context).pushNamed('/router/mine_vip_core', arguments: { - "rankLevel": curLevel, - "userInfo": userInfo, - "createTime": (userInfo != null) ? "${userInfo!.createTime}" : "", - "expendAmount": - double.tryParse(userInfo?.expendAmount ?? "0")?.toInt(), - }); + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed('/router/mine_vip_core', arguments: { + "rankLevel": curLevel, + "userInfo": userInfo, + "createTime": (userInfo != null) ? "${userInfo!.createTime}" : "", + "expendAmount": + double.tryParse(userInfo?.expendAmount ?? "0")?.toInt(), }); }, child: widget, diff --git a/lib/view_widget/mine_vip_view.dart b/lib/view_widget/mine_vip_view.dart index 70e3547d..46081b23 100644 --- a/lib/view_widget/mine_vip_view.dart +++ b/lib/view_widget/mine_vip_view.dart @@ -5,6 +5,7 @@ import 'package:huixiang/data/rank.dart'; import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -365,26 +366,20 @@ class MineVipView extends StatelessWidget { return GestureDetector( onTap: () { - SharedPreferences.getInstance().then((value) { - if (value.getString("token") == null || - value.getString("token") == "") { - LoginTipsDialog().show(context); - return; - } - // Navigator.of(context) - // .pushNamed('/router/mine_vip_level_page', arguments: { - // "rankLevel": curLevel, - // "createTime": (userInfo != null) ? "${userInfo.createTime}" : "", - // "points": (userInfo != null) ? int.tryParse(userInfo.points) : 0, - // }); - Navigator.of(context).pushNamed('/router/mine_vip_core', arguments: { + if (SharedInstance.instance.token.isEmpty) { + LoginTipsDialog().show(context); + return; + } + Navigator.of(context).pushNamed( + '/router/mine_vip_core', + arguments: { "rankLevel": curLevel, "userInfo": userInfo?.masterCardRankName, "createTime": (userInfo != null) ? "${userInfo!.createTime}" : "", "expendAmount": double.tryParse(userInfo?.expendAmount ?? "0")?.toInt(), - }); - }); + }, + ); }, child: widget, //(tag == null || tag == "") diff --git a/lib/view_widget/my_appbar.dart b/lib/view_widget/my_appbar.dart index 64c7872f..bfd21555 100644 --- a/lib/view_widget/my_appbar.dart +++ b/lib/view_widget/my_appbar.dart @@ -23,22 +23,22 @@ class MyAppBar extends StatelessWidget implements PreferredSizeWidget { MyAppBar( {this.onTap, - this.action, - this.actions, - this.bottom, - this.titleChild, - this.title, - this.toolbarHeight = kToolbarHeight, - this.background = const Color(0xFFF7F7F7), - this.leadingColor = Colors.black, - this.titleColor = Colors.black, - this.titleSize = 18, - this.systemUiOverlayStyle = SystemUiOverlayStyle.dark, - this.leading = true, - this.centerTitle = true, - this.exit}) + this.action, + this.actions, + this.bottom, + this.titleChild, + this.title, + this.toolbarHeight = kToolbarHeight, + this.background = const Color(0xFFF7F7F7), + this.leadingColor = Colors.black, + this.titleColor = Colors.black, + this.titleSize = 18, + this.systemUiOverlayStyle = SystemUiOverlayStyle.dark, + this.leading = true, + this.centerTitle = true, + this.exit}) : preferredSize = - Size.fromHeight(toolbarHeight + (bottom != null ? 35 : 0)) { + Size.fromHeight(toolbarHeight + (bottom != null ? 35 : 0)) { if (actions == null) actions = []; if (action != null) { actions!.add( @@ -46,7 +46,9 @@ class MyAppBar extends StatelessWidget implements PreferredSizeWidget { margin: EdgeInsets.only(right: 15), alignment: Alignment.center, child: GestureDetector( - onTap: onTap?.call(), + onTap: () { + onTap?.call(); + }, child: action, ), ), @@ -63,38 +65,38 @@ class MyAppBar extends StatelessWidget implements PreferredSizeWidget { systemOverlayStyle: systemUiOverlayStyle, leading: leading ? GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - if (exit == null) - Navigator.of(context).pop(); - else - exit!.call(); - }, - child: Icon( - Icons.arrow_back_ios, - color: leadingColor, - size: 22, - ), - ) + behavior: HitTestBehavior.opaque, + onTap: () { + if (exit == null) + Navigator.of(context).pop(); + else + exit!.call(); + }, + child: Icon( + Icons.arrow_back_ios, + color: leadingColor, + size: 22, + ), + ) : Container(), title: ((title == null || title == "") && titleChild != null) ? titleChild : GestureDetector( - onTap: () { - if (exit == null) - Navigator.of(context).pop(); - else - exit!.call(); - }, - child: Text( - title ?? "", - style: TextStyle( - color: titleColor, - fontWeight: MyFontWeight.medium, - fontSize: titleSize, - ), - ), - ), + onTap: () { + if (exit == null) + Navigator.of(context).pop(); + else + exit!.call(); + }, + child: Text( + title ?? "", + style: TextStyle( + color: titleColor, + fontWeight: MyFontWeight.medium, + fontSize: titleSize, + ), + ), + ), actions: actions, bottom: bottom, ); diff --git a/lib/view_widget/selector_store_dialog.dart b/lib/view_widget/selector_store_dialog.dart index 9e0dbda1..cfd26d53 100644 --- a/lib/view_widget/selector_store_dialog.dart +++ b/lib/view_widget/selector_store_dialog.dart @@ -6,6 +6,7 @@ import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SelectorStoreWidget extends StatefulWidget { @@ -27,12 +28,10 @@ class _SelectorStoreWidget extends State<SelectorStoreWidget> { @override void initState() { - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - // showLoading: true, - context: context, - token: value.getString("token")), - }); + apiService = ApiService(Dio(), + // showLoading: true, + context: context, + token: SharedInstance.instance.token); super.initState(); } @@ -78,7 +77,8 @@ class _SelectorStoreWidget extends State<SelectorStoreWidget> { color: Color(0xFF353535), ), ), - )), + ), + ), GestureDetector( onTap: () { setState(() { @@ -133,7 +133,8 @@ class _SelectorStoreWidget extends State<SelectorStoreWidget> { }, itemCount: widget.stores != null ? widget.stores.length : 0, ), - )), + ), + ), GestureDetector( onTap: () { if (widget.stores.length == 0) { @@ -172,7 +173,8 @@ class _SelectorStoreWidget extends State<SelectorStoreWidget> { ), alignment: Alignment.center, margin: EdgeInsets.only( - top: 14.h, bottom: 30.h, left: 16.w, right: 16.w), + top: 14.h, bottom: 30.h, left: 16.w, right: 16.w, + ), child: Text( S.of(context).queding, style: TextStyle( @@ -183,67 +185,6 @@ class _SelectorStoreWidget extends State<SelectorStoreWidget> { ), ), ), - // Row( - // mainAxisAlignment: MainAxisAlignment.center, - // crossAxisAlignment: CrossAxisAlignment.center, - // children: [ - // InkWell( - // onTap: () { - // Navigator.of(context).pop(); - // }, - // child: BorderText( - // text: S.of(context).quxiao, - // borderColor: Color(0xFF32A060), - // textColor: Color(0xFF32A060), - // radius: 4, - // fontSize: 16.sp, - // fontWeight: FontWeight.bold, - // borderWidth: 1.w, - // padding: EdgeInsets.symmetric( - // vertical: 12.h, - // horizontal: 42.w, - // ), - // ), - // ), - // SizedBox( - // width: 13.w, - // ), - // InkWell( - // onTap: () { - // if (widget.stores[selectIndex].posType.code == - // "NORMALSTORE") { - // Scan.toScan( - // context, - // widget.stores[selectIndex].id, - // widget.stores[selectIndex].tenantCode, - // widget.stores[selectIndex].storeName, - // ); - // } else { - // Navigator.of(context).pushNamed( - // '/router/store_order', - // arguments: { - // "id": widget.stores[selectIndex].id, - // "tenant": widget.stores[selectIndex].tenantCode, - // "storeName": widget.stores[selectIndex].storeName - // }, - // ); - // } - // }, - // child: RoundButton( - // text: S.of(context).queding, - // textColor: Colors.white, - // backgroup: Color(0xFF32A060), - // radius: 4, - // fontSize: 16.sp, - // fontWeight: FontWeight.bold, - // padding: EdgeInsets.symmetric( - // vertical: 12.h, - // horizontal: 42.w, - // ), - // ), - // ), - // ], - // ), ], ), ); @@ -252,7 +193,9 @@ class _SelectorStoreWidget extends State<SelectorStoreWidget> { Widget storeItem(Store store, position) { return Container( height: 52.h, - margin: EdgeInsets.only(bottom: 12.h, left: 14.w, right: 14.w), + margin: EdgeInsets.only( + bottom: 12.h, left: 14.w, right: 14.w, + ), child: Stack( alignment: Alignment.bottomRight, children: [ @@ -293,40 +236,6 @@ class _SelectorStoreWidget extends State<SelectorStoreWidget> { height: 20, fit: BoxFit.fill, ), - // MImage( - // store.logo, - // width: 28.w, - // height: 28.h, - // fit: BoxFit.cover, - // radius: BorderRadius.circular(2), - // errorSrc: "assets/image/default_1.webp", - // fadeSrc: "assets/image/default_1.webp", - // ), - // SizedBox( - // width: 12.w, - // ), - // Expanded( - // flex: 1, - // child: Text( - // store.storeName, - // style: TextStyle( - // color: Color(0xFF353535), - // fontSize: 16.sp, - // ), - // ), - // ), - // Checkbox( - // value: position == selectIndex, - // onChanged: (value) { - // setState(() { - // selectIndex = position; - // }); - // }, - // checkColor: Color(0xFFFFFFFF), - // fillColor: MaterialStateProperty.all(Color(0xFF39B54A)), - // materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, - // shape: CircleBorder(), - // ), ], ), ); diff --git a/lib/view_widget/update_dialog.dart b/lib/view_widget/update_dialog.dart index 92a020d8..b79dcd10 100644 --- a/lib/view_widget/update_dialog.dart +++ b/lib/view_widget/update_dialog.dart @@ -3,13 +3,12 @@ import 'dart:io'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter/material.dart'; import 'package:huixiang/data/app_update.dart'; +import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; -import 'package:shared_preferences/shared_preferences.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:url_launcher/url_launcher.dart'; -import '../generated/l10n.dart'; - class UpdateDialog extends StatefulWidget { final String version; final AppUpdate? appUpdate; @@ -143,8 +142,7 @@ class _UpdateDialog extends State<UpdateDialog> { } doNotUpdate() async { - SharedPreferences value = await SharedPreferences.getInstance(); - value.setString("appLastVersion", widget.appUpdate?.appLastVersion ?? ""); + SharedInstance.instance.saveAppLastVersion(widget.appUpdate?.appLastVersion ?? ""); Navigator.of(context).pop(); } @@ -158,4 +156,5 @@ class _UpdateDialog extends State<UpdateDialog> { throw 'Could not launch $url'; } } + } diff --git a/lib/view_widget/vip_dialog.dart b/lib/view_widget/vip_dialog.dart index dffc329e..d4ae8032 100644 --- a/lib/view_widget/vip_dialog.dart +++ b/lib/view_widget/vip_dialog.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/vip_benefit.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'custom_image.dart'; @@ -30,20 +31,17 @@ class _VipDialog extends State<VipDialog> { void initState() { super.initState(); - SharedPreferences.getInstance().then((value) { - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token") ?? "", - ); - queryBenefitList(); - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token ?? "", + ); + queryBenefitList(); } ///会员权益列表 queryBenefitList() async { - BaseListData<VipBenefit>? baseData = - await apiService?.benefitList().catchError((onError) { + BaseListData<VipBenefit>? baseData = await apiService?.benefitList().catchError((onError) { return BaseListData<VipBenefit>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { @@ -51,8 +49,7 @@ class _VipDialog extends State<VipDialog> { if (baseData!.data?.isNotEmpty ?? false) { vipBenefitList.clear(); vipBenefitList.addAll(baseData.data!); - vipBenefitList - .sort((a, b) => ((a.sort ?? 0)).compareTo((b.sort ?? 0))); + vipBenefitList.sort((a, b) => ((a.sort ?? 0)).compareTo((b.sort ?? 0))); } }); } @@ -114,45 +111,26 @@ class _VipDialog extends State<VipDialog> { ), Container( width: MediaQuery.of(context).size.width, - height: ((((vipBenefitList == null - ? 0 - : vipBenefitList.length) ~/ - 3 + - ((vipBenefitList == null - ? 0 - : vipBenefitList - .length) % - 3 > - 0 - ? 1 - : 0)) * - 90.h) > - MediaQuery.of(context).size.height / 2 + height: ((((vipBenefitList.length) ~/ 3 + + ((vipBenefitList.length) % 3 > 0 ? 1 : 0)) * 90.h) > MediaQuery.of(context).size.height / 2 ? MediaQuery.of(context).size.height / 2 - : (((vipBenefitList == null - ? 0 - : vipBenefitList.length) ~/ - 3 + - ((vipBenefitList == null - ? 0 - : vipBenefitList.length) % - 3 > - 0 - ? 1 - : 0)) * - 90.h)) + : (((vipBenefitList.length) ~/ 3 + ((vipBenefitList.length) % 3 > 0 ? 1 : 0)) * 90.h)) .toDouble(), - child: vipUpgrade()), + child: vipUpgrade(), + ), GestureDetector( onTap: () { Navigator.of(context).popAndPushNamed( '/router/legal_right_details', arguments: { "vipBenefitList": vipBenefitList, - }); + }, + ); }, child: Container( - margin: EdgeInsets.only(left: 32, right: 32, bottom: 20), + margin: EdgeInsets.only( + left: 32, right: 32, bottom: 20, + ), decoration: BoxDecoration( gradient: new LinearGradient( begin: Alignment.centerLeft, @@ -160,7 +138,8 @@ class _VipDialog extends State<VipDialog> { colors: [ Color(0xFFFFDCA1), Color(0xFFFAE4C0), - ]), + ], + ), borderRadius: BorderRadius.circular(22.5), ), width: MediaQuery.of(context).size.width, @@ -194,7 +173,7 @@ class _VipDialog extends State<VipDialog> { ///会员升级权益列表 Widget vipUpgrade() { return GridView.builder( - itemCount: vipBenefitList == null ? 0 : vipBenefitList.length, + itemCount: vipBenefitList.length, shrinkWrap: true, physics: BouncingScrollPhysics(), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( diff --git a/lib/vip/vip_page.dart b/lib/vip/vip_page.dart index b23955df..06af4a6f 100644 --- a/lib/vip/vip_page.dart +++ b/lib/vip/vip_page.dart @@ -8,6 +8,7 @@ import 'package:huixiang/data/vip_card_home.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/vip/vip_view/exclusive_coupon.dart'; import 'package:huixiang/vip/vip_view/vip_top.dart'; @@ -48,18 +49,16 @@ class _VipPageState extends State<VipPage> with AutomaticKeepAliveClientMixin { ///查询会员信息 queryUserBalance() async { try{ - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - showLoading: true - ); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: true + ); BaseData<UserInfo>? baseData = await apiService?.queryInfo().catchError((onError) { _refreshController.refreshFailed(); - _refreshController.loadFailed();}); + _refreshController.loadFailed(); + }); if (baseData?.isSuccess ?? false) { userInfo = baseData?.data; if (mounted) setState(() {}); @@ -72,7 +71,7 @@ class _VipPageState extends State<VipPage> with AutomaticKeepAliveClientMixin { _refreshController.refreshFailed(); _refreshController.loadFailed(); } - }finally{ + } finally { setState((){}); } } @@ -80,19 +79,14 @@ class _VipPageState extends State<VipPage> with AutomaticKeepAliveClientMixin { ///Vip季卡,月卡,首页接口(暂不用) queryVipHome() async { try{ - if (apiService == null) { - SharedPreferences value = await SharedPreferences.getInstance(); - apiService = ApiService( - Dio(), - context: context, - token: value.getString("token"), - showLoading: true - ); - } + apiService ??= ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: true + ); BaseData<VipCardHome>? baseData = await apiService?.vipCardIndex().catchError((onError) { - SmartDialog.showToast(AppUtils.dioErrorTypeToString(onError.type), - alignment: Alignment.center); _refreshController.loadFailed(); _refreshController.refreshFailed(); }); @@ -100,14 +94,14 @@ class _VipPageState extends State<VipPage> with AutomaticKeepAliveClientMixin { vipHome = baseData?.data; _refreshController.refreshCompleted(); _refreshController.loadComplete(); - }else{ + } else { if (baseData?.msg?.isNotEmpty ?? false) { SmartDialog.showToast(baseData?.msg ?? "", alignment: Alignment.center); } _refreshController.loadFailed(); _refreshController.refreshFailed(); } - }finally{ + } finally { setState((){}); } } diff --git a/lib/web/web_page.dart b/lib/web/web_page.dart index e23acadd..0522b5a9 100644 --- a/lib/web/web_page.dart +++ b/lib/web/web_page.dart @@ -10,6 +10,7 @@ import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/examine_instance.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/share_dialog.dart'; import 'package:huixiang/view_widget/tips_dialog.dart'; @@ -57,13 +58,12 @@ class _WebPage extends State<WebPage> with WidgetsBindingObserver { super.initState(); WidgetsBinding.instance.addObserver(this); commentFocus.addListener(_focusNodeListener); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, - token: value.getString('token'), - showLoading: true), - queryHtml() - }); + apiService = ApiService(Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: true, + ); + queryHtml(); } bool isKeyBoardShow = false; @@ -135,17 +135,17 @@ class _WebPage extends State<WebPage> with WidgetsBindingObserver { } queryHtml() async { - SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService(Dio(), // showLoading: true, context: context, - token: value.getString("token")); + token: SharedInstance.instance.token, + ); if (widget.arguments?["activityId"] != null) { BaseData<Activity>? baseData = await apiService ?.activityInfo(widget.arguments!["activityId"]) .catchError((onError) { - return Future.value(null); + return BaseData<Activity>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { activity = baseData?.data; @@ -156,7 +156,7 @@ class _WebPage extends State<WebPage> with WidgetsBindingObserver { BaseData<Article>? baseData = await apiService ?.informationInfo(widget.arguments!["articleId"]) .catchError((onError) { - return Future.value(null); + return BaseData<Article>()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { article = baseData?.data; @@ -170,11 +170,10 @@ class _WebPage extends State<WebPage> with WidgetsBindingObserver { BaseData? baseData = await apiService?.memberComment({ "content": content, "parentId": parenId, - "relationalId": - widget.arguments?["activityId"] ?? widget.arguments?["articleId"], + "relationalId": widget.arguments?["activityId"] ?? widget.arguments?["articleId"], "relationalType": 1 }).catchError((error) { - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { CommentListState _commentList = @@ -237,10 +236,9 @@ class _WebPage extends State<WebPage> with WidgetsBindingObserver { //给文章/活动点赞 _queryInformationLikes() async { BaseData? baseData = await apiService - ?.informationLikes( - widget.arguments?["activityId"] ?? widget.arguments?["articleId"]) + ?.informationLikes(widget.arguments?["activityId"] ?? widget.arguments?["articleId"]) .catchError((onError) { - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { if (article != null) { @@ -253,8 +251,6 @@ class _WebPage extends State<WebPage> with WidgetsBindingObserver { article!.liked = !(article!.liked ?? false); } commentKey.currentState?.setState(() {}); - } else { - // SmartDialog.showToast(baseData.msg, alignment: Alignment.center); } } diff --git a/lib/web/web_turntable_activity.dart b/lib/web/web_turntable_activity.dart index 024767e9..7643d71a 100644 --- a/lib/web/web_turntable_activity.dart +++ b/lib/web/web_turntable_activity.dart @@ -1,7 +1,6 @@ - import 'package:flutter/material.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/my_appbar.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:webview_flutter/webview_flutter.dart'; class WebTurntableActivity extends StatefulWidget { @@ -16,7 +15,8 @@ class WebTurntableActivity extends StatefulWidget { } } -class _WebTurntableActivity extends State<WebTurntableActivity> with WidgetsBindingObserver { +class _WebTurntableActivity extends State<WebTurntableActivity> + with WidgetsBindingObserver { final ScrollController scrollController = ScrollController(); String? token; @@ -27,28 +27,27 @@ class _WebTurntableActivity extends State<WebTurntableActivity> with WidgetsBind super.initState(); WidgetsBinding.instance.addObserver(this); - SharedPreferences.getInstance().then((value) => { - token = value.getString('token'), - _webViewController = WebViewController() - ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setNavigationDelegate( - NavigationDelegate( - onProgress: (int progress) { - // Update loading bar. - }, - onPageStarted: (String url) {}, - onPageFinished: (String url) {}, - onWebResourceError: (WebResourceError error) {}, - onNavigationRequest: (NavigationRequest request) { - // if (request.url.startsWith('https://www.youtube.com/')) { - // return NavigationDecision.prevent; - // } - return NavigationDecision.navigate; - }, - ), - ) - ..loadRequest(Uri.parse("http://192.168.10.90:5500/lottery.html?token=${token}")) - }); + token = SharedInstance.instance.token; + _webViewController = WebViewController() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (int progress) { + // Update loading bar. + }, + onPageStarted: (String url) {}, + onPageFinished: (String url) {}, + onWebResourceError: (WebResourceError error) {}, + onNavigationRequest: (NavigationRequest request) { + // if (request.url.startsWith('https://www.youtube.com/')) { + // return NavigationDecision.prevent; + // } + return NavigationDecision.navigate; + }, + ), + ) + ..loadRequest( + Uri.parse("http://192.168.10.90:5500/lottery.html?token=${token}")); } @override diff --git a/lib/web/web_view/comment_list.dart b/lib/web/web_view/comment_list.dart index 8ecc42f6..d3ec5f39 100644 --- a/lib/web/web_view/comment_list.dart +++ b/lib/web/web_view/comment_list.dart @@ -7,6 +7,7 @@ import 'package:huixiang/data/member_comment.dart'; import 'package:huixiang/data/page.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; +import 'package:huixiang/utils/shared_preference.dart'; import 'package:huixiang/view_widget/comment_menu.dart'; import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart'; @@ -41,41 +42,41 @@ class CommentListState extends State<CommentList> { //评论点赞 queryCommentLike(String id) async { - SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); - String token = sharedPreferences.getString("token") ?? ""; - if (token == "") { + if (SharedInstance.instance.token.isEmpty) { LoginTipsDialog().show(context); return; } BaseData? baseData = await apiService?.commentLike(id).catchError((error) { - return Future.value(null); + return BaseData()..isSuccess = false; }); if (baseData?.isSuccess ?? false) { - memberList.forEach((element) { - if (element.id == id) { - int likes = element.likes ?? 0; - if (element.liked ?? false) { - element.likes = (likes - 1); - element.liked = false; - } else { - element.likes = (likes + 1); - element.liked = true; + memberList.forEach( + (element) { + if (element.id == id) { + int likes = element.likes ?? 0; + if (element.liked ?? false) { + element.likes = (likes - 1); + element.liked = false; + } else { + element.likes = (likes + 1); + element.liked = true; + } } - } - }); + }, + ); } } @override void initState() { super.initState(); - SharedPreferences.getInstance().then((value) => { - apiService = ApiService(Dio(), - context: context, - token: value.getString('token'), - showLoading: true), - queryMemberCommentList() - }); + apiService = ApiService( + Dio(), + context: context, + token: SharedInstance.instance.token, + showLoading: true, + ); + queryMemberCommentList(); } @override @@ -223,25 +224,23 @@ class CommentListState extends State<CommentList> { FocusScope.of(context).requestFocus(FocusNode()); return; } - SharedPreferences.getInstance().then((value) { - SmartDialog.show( - builder: (ctx) { - return CommentMenu( - (type) { - SmartDialog.dismiss(); - if (type == "huifu") { - widget.reply(memberComment); - } else if (type == "shanchu") { - widget.delCommentTips(memberComment); - } - }, - isSelf: userId == value.getString("userId"), - ); - }, - alignment: Alignment.bottomCenter, - animationTime: Duration(milliseconds: 300), - ); - }); + SmartDialog.show( + builder: (ctx) { + return CommentMenu( + (type) { + SmartDialog.dismiss(); + if (type == "huifu") { + widget.reply(memberComment); + } else if (type == "shanchu") { + widget.delCommentTips(memberComment); + } + }, + isSelf: userId == SharedInstance.instance.userId, + ); + }, + alignment: Alignment.bottomCenter, + animationTime: Duration(milliseconds: 300), + ); } Widget commentItem(MemberComment member, int index) { @@ -395,11 +394,9 @@ class CommentListState extends State<CommentList> { ), ), ), - )), - SizedBox( - height: 12.h, + ), ), - if (member.parentUserName != "" || member.parentContent != "") + if ((member.parentUserName?.isNotEmpty ?? false) || (member.parentContent?.isNotEmpty ?? false)) Container( margin: EdgeInsets.only(left: 68.w, right: 16.w), decoration: BoxDecoration( diff --git a/lib/web/web_view/input_comment.dart b/lib/web/web_view/input_comment.dart index 75a0be7a..ecacae4a 100644 --- a/lib/web/web_view/input_comment.dart +++ b/lib/web/web_view/input_comment.dart @@ -224,26 +224,25 @@ class _InputComment extends State<InputComment> { child: SizedBox( height: widget.keyboard == -1 ? 270 : widget.keyboard, width: MediaQuery.of(context).size.width, - child: - EmojiPicker( + child: EmojiPicker( textEditingController: widget.commentTextController, config: Config( emojiViewConfig: EmojiViewConfig( columns: 7, - emojiSizeMax: 32 * (Platform.isIOS ? 1.10 : 1.0), + emojiSizeMax: 28 * (Platform.isIOS ? 1.10 : 1.0), verticalSpacing: 0, horizontalSpacing: 0, + backgroundColor: const Color(0xFFF2F2F2), gridPadding: EdgeInsets.zero, - recentsLimit: 28, - buttonMode: ButtonMode.MATERIAL, + recentsLimit: 35, replaceEmojiOnLimitExceed: false, - loadingIndicator: const SizedBox.shrink(), - noRecents:Text( + noRecents: Text( "最近使用", style: TextStyle(fontSize: 20, color: Colors.black26), textAlign: TextAlign.center, ), - backgroundColor: const Color(0xFFF2F2F2), + loadingIndicator: const SizedBox.shrink(), + buttonMode: ButtonMode.MATERIAL, ), skinToneConfig: SkinToneConfig( enabled: true, @@ -252,17 +251,19 @@ class _InputComment extends State<InputComment> { ), categoryViewConfig: CategoryViewConfig( initCategory: Category.RECENT, + iconColor: Colors.grey, iconColorSelected: Colors.blue, backspaceColor: Colors.blue, - tabIndicatorAnimDuration: Duration(milliseconds: 0), categoryIcons: const CategoryIcons(), - iconColor: Colors.grey, + tabIndicatorAnimDuration: Duration(milliseconds: 0), ), bottomActionBarConfig: BottomActionBarConfig( - buttonIconColor: Colors.grey, + backgroundColor: Colors.transparent, + buttonIconColor: Colors.blue, + showBackspaceButton: true, + showSearchViewButton: false, ), - // indicatorColor: Colors.blue, - swapCategoryAndBottomBar: true, + swapCategoryAndBottomBar: false, checkPlatformCompatibility: true, ), ), diff --git a/pubspec.lock b/pubspec.lock index db2f1f7e..96bcd59d 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -217,6 +217,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.18.0" + color_thief_dart: + dependency: "direct main" + description: + name: color_thief_dart + sha256: b3410cf809ca877e64b59b91a4a5e5eb2316ebe3d148b19ba1680eac2a08dc76 + url: "https://pub.dev" + source: hosted + version: "0.1.0" convert: dependency: transitive description: @@ -470,6 +478,54 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0-beta.2" + flutter_keyboard_visibility: + dependency: "direct main" + description: + name: flutter_keyboard_visibility + sha256: "98664be7be0e3ffca00de50f7f6a287ab62c763fc8c762e0a21584584a3ff4f8" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_keyboard_visibility_linux: + dependency: transitive + description: + name: flutter_keyboard_visibility_linux + sha256: "6fba7cd9bb033b6ddd8c2beb4c99ad02d728f1e6e6d9b9446667398b2ac39f08" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_keyboard_visibility_macos: + dependency: transitive + description: + name: flutter_keyboard_visibility_macos + sha256: c5c49b16fff453dfdafdc16f26bdd8fb8d55812a1d50b0ce25fc8d9f2e53d086 + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_keyboard_visibility_platform_interface: + dependency: transitive + description: + name: flutter_keyboard_visibility_platform_interface + sha256: e43a89845873f7be10cb3884345ceb9aebf00a659f479d1c8f4293fcb37022a4 + url: "https://pub.dev" + source: hosted + version: "2.0.0" + flutter_keyboard_visibility_web: + dependency: transitive + description: + name: flutter_keyboard_visibility_web + sha256: d3771a2e752880c79203f8d80658401d0c998e4183edca05a149f5098ce6e3d1 + url: "https://pub.dev" + source: hosted + version: "2.0.0" + flutter_keyboard_visibility_windows: + dependency: transitive + description: + name: flutter_keyboard_visibility_windows + sha256: fc4b0f0b6be9b93ae527f3d527fb56ee2d918cd88bbca438c478af7bcfd0ef73 + url: "https://pub.dev" + source: hosted + version: "1.0.0" flutter_localizations: dependency: "direct main" description: flutter diff --git a/pubspec.yaml b/pubspec.yaml index b8a35a2b..f543624f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -60,7 +60,7 @@ dependencies: pull_to_refresh: ^2.0.0 # Null safety number_precision: ^2.0.2+1 - + flutter_keyboard_visibility: ^6.0.0 permission_handler: ^11.3.0 geolocator: ^7.7.1 @@ -96,15 +96,12 @@ dependencies: #多图, 裁剪 image_pickers: 2.0.4+8 - - # flutter_scankit: ^1.2.0 - # qrscan: ^0.3.1 scan: ^1.6.0 path_provider: ^2.1.4 network_to_file_image: ^7.0.0 image_gallery_saver: ^2.0.3 - + flutter_slidable: ^3.1.2 flutter_html: ^3.0.0-beta.2 flutter_html_svg: ^3.0.0-beta.2 flutter_html_iframe: ^3.0.0-beta.2 @@ -119,9 +116,7 @@ dependencies: # flutter_ffmpeg: ^0.4.2 package_info_plus: ^8.0.2 - sharesdk_plugin: ^1.3.14 - flutter_spinkit: ^5.2.0 # flutter_easyloading: ^3.0.5 @@ -134,18 +129,12 @@ dependencies: # ai_decimal_accuracy: ^1.1.0 table_calendar: ^3.0.9 - - flutter_slidable: ^3.0.1 - emoji_picker_flutter: ^2.1.1 - mqtt_client: ^10.3.0 - shimmer: ^3.0.0 # 时间选择器 flutter_datetime_picker_plus: ^2.1.0 - qiniu_flutter_sdk: ^0.7.0 # qiniu_flutter_sdk: # path: qiniu-dart-sdk/flutter @@ -157,6 +146,8 @@ dependencies: syncfusion_flutter_datepicker: ^24.2.9 protobuf: ^3.1.0 + color_thief_dart: ^0.1.0 + dev_dependencies: flutter_test: sdk: flutter