Browse Source

UI修改0115:1415

dart3_last
fff 1 week ago
parent
commit
f79e83848a
  1. 162
      lib/address/address_map_page.dart
  2. 14
      lib/address/edit_address_page.dart
  3. 16
      lib/base_state.dart
  4. 7
      lib/community/community_child_list.dart
  5. 100
      lib/community/community_child_page.dart
  6. 43
      lib/community/community_course.dart
  7. 51
      lib/community/community_details.dart
  8. 12
      lib/community/community_list.dart
  9. 33
      lib/community/community_view/class_details.dart
  10. 364
      lib/community/community_view/community_dynamic.dart
  11. 39
      lib/community/community_view/course_banner.dart
  12. 1
      lib/community/community_view/home_class.dart
  13. 4
      lib/community/headlines/activity_top_list.dart
  14. 32
      lib/community/headlines/article_list.dart
  15. 14
      lib/community/headlines/article_page.dart
  16. 38
      lib/community/headlines/headlines_banner.dart
  17. 2
      lib/community/headlines/headlines_collection.dart
  18. 88
      lib/community/headlines/headlines_column_details.dart
  19. 38
      lib/community/new_community_details.dart
  20. 1
      lib/community/order_page.dart
  21. 7
      lib/community/photo_view_gallery_screen.dart
  22. 27
      lib/community/release_dynamic.dart
  23. 6
      lib/community/report/report_notice.dart
  24. 290
      lib/community/report/report_page.dart
  25. 2
      lib/community/report/report_success.dart
  26. 207
      lib/community/share_trends.dart
  27. 16
      lib/constant.dart
  28. 2
      lib/data/article.dart
  29. 6
      lib/data/article.g.dart
  30. 32
      lib/data/vip_card.dart
  31. 9
      lib/home/activity_list_page.dart
  32. 316
      lib/home/founder_story_page.dart
  33. 55
      lib/home/guide_page.dart
  34. 63
      lib/home/help_farmers/help_farmers_page.dart
  35. 108
      lib/home/home_page.dart
  36. 6
      lib/home/home_view/activity_list.dart
  37. 2
      lib/home/home_view/brand_view.dart
  38. 27
      lib/home/home_view/coupon.dart
  39. 1
      lib/home/home_view/discount_zone.dart
  40. 49
      lib/home/home_view/featured_acticvity.dart
  41. 7
      lib/home/home_view/founder_store.dart
  42. 2
      lib/home/home_view/happy_help_farmers.dart
  43. 33
      lib/home/home_view/home_banner.dart
  44. 10
      lib/home/home_view/home_integral_store.dart
  45. 8
      lib/home/home_view/home_recommend_goods.dart
  46. 11
      lib/home/home_view/hot_article.dart
  47. 96
      lib/home/home_view/quick_order.dart
  48. 1
      lib/home/home_view/shortcut_operation.dart
  49. 31
      lib/home/home_view/sign_view.dart
  50. 3
      lib/home/home_view/top_selling_list.dart
  51. 1
      lib/home/home_view/union_entry.dart
  52. 1
      lib/home/home_view/welfare_core.dart
  53. 16
      lib/home/huixiang_brand_page.dart
  54. 36
      lib/home/huixiang_view/huixiang_banner.dart
  55. 1
      lib/home/huixiang_view/origin_info.dart
  56. 23
      lib/home/points_mall_page.dart
  57. 14
      lib/home/points_mall_view/point_mall_user.dart
  58. 5
      lib/home/points_mall_view/points_goods_title.dart
  59. 3
      lib/home/points_mall_view/points_goods_view.dart
  60. 33
      lib/home/points_mall_view/points_mall_banner.dart
  61. 8
      lib/home/trading_card_page.dart
  62. 36
      lib/home/welfare_exchange.dart
  63. 72
      lib/home/welfare_page.dart
  64. 9
      lib/im/SocketClient.dart
  65. 1
      lib/im/add_friend.dart
  66. 534
      lib/im/chat_details_page.dart
  67. 18
      lib/im/chat_friend_group.dart
  68. 12
      lib/im/chat_setting.dart
  69. 277
      lib/im/contact_share.dart
  70. 4
      lib/im/database/hx_database.dart
  71. 4
      lib/im/database/message.dart
  72. 143
      lib/im/im_search.dart
  73. 35
      lib/im/im_view/friend_groip_list.dart
  74. 377
      lib/im/im_view/im_page.dart
  75. 36
      lib/im/im_view/on_chat_msg_instance.dart
  76. 131
      lib/integral/integral_detailed_page.dart
  77. 50
      lib/integral/integral_page.dart
  78. 51
      lib/integral/intergra_view/integral_vip.dart
  79. 66
      lib/integral_store/integral_store_details_page.dart
  80. 4
      lib/login/captcha/block_puzzle_captcha.dart
  81. 119
      lib/login/login_page.dart
  82. 80
      lib/login/new_login_page.dart
  83. 160
      lib/main.dart
  84. 100
      lib/main_page.dart
  85. 8
      lib/message/main_message_page.dart
  86. 14
      lib/message/real_time_info_page.dart
  87. 27
      lib/message/system_details.dart
  88. 439
      lib/message/system_message.dart
  89. 26
      lib/message/system_notice.dart
  90. 10
      lib/mine/coupon_page.dart
  91. 7
      lib/mine/coupons_page.dart
  92. 20
      lib/mine/fans_page.dart
  93. 14
      lib/mine/follow_page.dart
  94. 27
      lib/mine/invitation_record.dart
  95. 10
      lib/mine/manage_address_page.dart
  96. 10
      lib/mine/mine_card_invalid_page.dart
  97. 14
      lib/mine/mine_greenery.dart
  98. 57
      lib/mine/mine_page.dart
  99. 396
      lib/mine/mine_shop_details.dart
  100. 68
      lib/mine/mine_shop_page.dart
  101. Some files were not shown because too many files have changed in this diff Show More

162
lib/address/address_map_page.dart

@ -9,6 +9,7 @@ import 'package:geolocator/geolocator.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/location.dart'; import 'package:huixiang/utils/location.dart';
import 'package:huixiang/utils/shared_preference.dart';
import 'package:huixiang/view_widget/request_permission.dart'; import 'package:huixiang/view_widget/request_permission.dart';
import 'package:permission_handler/permission_handler.dart' as PH; import 'package:permission_handler/permission_handler.dart' as PH;
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -46,10 +47,12 @@ class _AddressMapPage extends State<AddressMapPage> {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(
apiService = ApiService(Dio(), Dio(),
context: context, token: value.getString('token')), context: context,
}); token: SharedInstance.instance.token,
);
LocationInstance.getInstance().startLocation(context, (Position? result) { LocationInstance.getInstance().startLocation(context, (Position? result) {
print("event: $result"); print("event: $result");
if (result?.latitude != null && result?.longitude != null) { if (result?.latitude != null && result?.longitude != null) {
@ -62,8 +65,7 @@ class _AddressMapPage extends State<AddressMapPage> {
heading: 0, heading: 0,
speed: 0, speed: 0,
speedAccuracy: 0); speedAccuracy: 0);
LocationInstance.getInstance() LocationInstance.getInstance().getAddress(result.latitude, result.longitude)
.getAddress(result.latitude, result.longitude)
?.then((value) { ?.then((value) {
if (value != null) { if (value != null) {
city = value.city ?? ""; city = value.city ?? "";
@ -242,158 +244,22 @@ class _AddressMapPage extends State<AddressMapPage> {
}, },
heightRatioWithWidth: 0.82, 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; 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 { saveLatLng(Position? latLng) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedInstance.instance.saveLatLng(latLng);
await prefs.setString("latitude", "${latLng?.latitude}");
await prefs.setString("longitude", "${latLng?.longitude}");
} }
// 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
body: Column( body: Column(
children: [ children: [
searchWidget(), 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<OneSequenceGestureRecognizer>>[
// // Factory<OneSequenceGestureRecognizer>(
// // () => 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( Expanded(
child: Container( child: Container(
child: ListView.separated( child: ListView.separated(
@ -464,14 +330,16 @@ class _AddressMapPage extends State<AddressMapPage> {
padding: EdgeInsets.fromLTRB(10, 6, 16, 6), padding: EdgeInsets.fromLTRB(10, 6, 16, 6),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(4)), borderRadius: BorderRadius.all(
Radius.circular(4),
),
boxShadow: [ boxShadow: [
BoxShadow( BoxShadow(
color: Colors.black.withAlpha(12), color: Colors.black.withAlpha(12),
offset: Offset(0, 3), offset: Offset(0, 3),
blurRadius: 14, blurRadius: 14,
spreadRadius: 0, spreadRadius: 0,
) ),
], ],
), ),
child: Row( child: Row(

14
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/address.dart';
import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/base_data.dart';
import 'package:huixiang/retrofit/retrofit_api.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/my_appbar.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
@ -32,11 +33,11 @@ class _EditAddressPage extends State<EditAddressPage> {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(Dio(),
apiService = ApiService(Dio(), context: context,
context: context, token: value.getString('token')), token: SharedInstance.instance.token,
queryAddress(), );
}); queryAddress();
} }
Address? preAddress; Address? preAddress;
@ -45,8 +46,7 @@ class _EditAddressPage extends State<EditAddressPage> {
preAddress = Address.fromJson(widget.arguments); preAddress = Address.fromJson(widget.arguments);
nameController.text = "${preAddress?.username}"; nameController.text = "${preAddress?.username}";
mobileController.text = "${preAddress?.phone}"; mobileController.text = "${preAddress?.phone}";
addressController.text = addressController.text = "${preAddress?.province}${preAddress?.city}${preAddress?.area}";
"${preAddress?.province}${preAddress?.city}${preAddress?.area}";
houseNumberController.text = "${preAddress?.addressStr}"; houseNumberController.text = "${preAddress?.addressStr}";
setState(() {}); setState(() {});
} }

16
lib/base_state.dart

@ -1,7 +1,9 @@
import 'dart:convert'; import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:huixiang/utils/bridge.dart'; import 'package:huixiang/utils/bridge.dart';
import 'package:huixiang/utils/shared_preference.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
abstract class BaseState<T extends StatefulWidget> extends State<T> abstract class BaseState<T extends StatefulWidget> extends State<T>
@ -41,16 +43,16 @@ abstract class BaseState<T extends StatefulWidget> extends State<T>
pushRoute() async { pushRoute() async {
String startIntent = await Bridge.getStartIntent(); String startIntent = await Bridge.getStartIntent();
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
print("intent:$startIntent"); print("intent:$startIntent");
String pushData = ""; String pushData = "";
if (startIntent != null && startIntent != "") { if (startIntent.isNotEmpty) {
pushData = startIntent; pushData = startIntent;
} else { } else {
pushData = sharedPreferences.getString("pushData") ?? ""; pushData = SharedInstance.instance.pushData;
} }
if (pushData == null || pushData == "") return; if (pushData.isEmpty) return;
Map<String, dynamic> pushMap = jsonDecode(pushData); Map<String, dynamic>? pushMap = jsonDecode(pushData);
if (pushMap != null) { if (pushMap != null) {
String routeName = ""; String routeName = "";
Map<String, dynamic> params = {}; Map<String, dynamic> params = {};
@ -108,8 +110,8 @@ abstract class BaseState<T extends StatefulWidget> extends State<T>
params["id"] = pushMap["info"]; params["id"] = pushMap["info"];
break; break;
} }
sharedPreferences.setString("pushData", ""); SharedInstance.instance.savePushData();
print("xgPushClickAction: routeName: $routeName"); debugPrint("xgPushClickAction: routeName: $routeName");
if (routeName != "") { if (routeName != "") {
Navigator.of(context).pushNamed(routeName, arguments: params); Navigator.of(context).pushNamed(routeName, arguments: params);
} }

7
lib/community/community_child_list.dart

@ -1,8 +1,10 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/base_data.dart';
import 'package:huixiang/data/comunity_comment.dart'; import 'package:huixiang/data/comunity_comment.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
@ -33,6 +35,11 @@ class _CommunityChildList extends State<CommunityChildList> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
apiService = ApiService(
Dio(),
context: context,
token: SharedInstance.instance.token,
);
_onRefresh(); _onRefresh();
} }

100
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/comunity_comment.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:huixiang/view_widget/no_data_view.dart';
@ -65,7 +66,7 @@ class CommunityChildPageState extends State<CommunityChildPage>
} }
/// ///
queryCommunity(String? searchKey) async { Future queryCommunity({String? searchKey}) async {
if (!isRefresh) { if (!isRefresh) {
isRefresh = true; isRefresh = true;
return; return;
@ -74,14 +75,12 @@ class CommunityChildPageState extends State<CommunityChildPage>
return; return;
} }
isLoadingData = true; isLoadingData = true;
if (apiService == null) { userId = SharedInstance.instance.userId;
SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService(Dio(),
userId = value.getString('userId'); context: context,
apiService = ApiService(Dio(), token: SharedInstance.instance.token,
context: context, showLoading: false,
token: value.getString("token"), );
showLoading: false);
}
if (isLoadMore) { if (isLoadMore) {
pageNum += 1; pageNum += 1;
isLoadMore = false; isLoadMore = false;
@ -103,25 +102,52 @@ class CommunityChildPageState extends State<CommunityChildPage>
}); });
refreshController.refreshCompleted(); refreshController.refreshCompleted();
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
if (baseData?.data?.list?.isNotEmpty ?? false) if (baseData?.data?.list?.isNotEmpty ?? false) {
articles.forEach((element) { if (searchKey != null) {
if (element.id == searchKey) { articles.forEach((element) {
element.content = jsonEncode(baseData?.data?.list?[0].subjectInfo); if (element.id == searchKey) {
element.mainTitle = baseData?.data?.list?[0].subject; element.content = jsonEncode(baseData?.data?.list?[0].subjectInfo);
element.followed = baseData?.data?.list?[0].selfFollow; element.mainTitle = baseData?.data?.list?[0].subject;
element.liked = baseData?.data?.list?[0].selfLike; element.followed = baseData?.data?.list?[0].selfFollow;
element.authorHeadImg = baseData?.data?.list?[0].memberInfo?.avatar; element.liked = baseData?.data?.list?[0].selfLike;
element.authorName = baseData?.data?.list?[0].memberInfo?.nickname; element.authorHeadImg = baseData?.data?.list?[0].memberInfo?.avatar;
element.location = baseData?.data?.list?[0].location; element.authorName = baseData?.data?.list?[0].memberInfo?.nickname;
element.createTime = baseData?.data?.list?[0].createTime; element.location = baseData?.data?.list?[0].location;
element.author = baseData?.data?.list?[0].memberInfo?.mid; element.createTime = baseData?.data?.list?[0].createTime;
element.viewers = baseData?.data?.list?[0].viewers; element.author = baseData?.data?.list?[0].memberInfo?.mid;
element.likes = baseData?.data?.list?[0].likes; element.viewers = baseData?.data?.list?[0].viewers;
element.comments = baseData?.data?.list?[0].comments; element.likes = baseData?.data?.list?[0].likes;
this.isRefresh = false; element.comments = baseData?.data?.list?[0].comments;
setState(() {}); 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; isLoadingData = false;
@ -131,7 +157,7 @@ class CommunityChildPageState extends State<CommunityChildPage>
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context); super.build(context);
return FutureBuilder( return FutureBuilder(
future: queryCommunity(null), future: queryCommunity(),
builder: (context, position) { builder: (context, position) {
return Stack( return Stack(
alignment: Alignment.bottomRight, alignment: Alignment.bottomRight,
@ -139,7 +165,7 @@ class CommunityChildPageState extends State<CommunityChildPage>
SmartRefresher( SmartRefresher(
controller: refreshController, controller: refreshController,
enablePullDown: true, enablePullDown: true,
enablePullUp: (articles.length == 0) ? false:true, enablePullUp: articles.isNotEmpty,
physics: BouncingScrollPhysics(), physics: BouncingScrollPhysics(),
header: MyHeader(), header: MyHeader(),
footer: CustomFooter( footer: CustomFooter(
@ -152,7 +178,7 @@ class CommunityChildPageState extends State<CommunityChildPage>
isLoadMore = true; isLoadMore = true;
setState(() {}); setState(() {});
}, },
child: (articles.length == 0) child: (articles.isEmpty)
? NoDataView( ? NoDataView(
src: "assets/image/guan_zhu.webp", src: "assets/image/guan_zhu.webp",
isShowBtn: false, isShowBtn: false,
@ -173,11 +199,10 @@ class CommunityChildPageState extends State<CommunityChildPage>
userId: userId, userId: userId,
isList: true, isList: true,
exitFull: () { exitFull: () {
// setState(() { queryCommunity(searchKey: articles[position].id);
// onRefresh(); },
// }); removalDynamic: () {
queryCommunity().then((value) => setState(() {}));
queryCommunity(articles[position].id);
}, },
), ),
onTap: () { onTap: () {
@ -188,12 +213,9 @@ class CommunityChildPageState extends State<CommunityChildPage>
"userId": userId, "userId": userId,
}, },
).then((value) { ).then((value) {
// onRefresh(); queryCommunity(searchKey: articles[position].id);
// setState(() {});
queryCommunity(articles[position].id);
}); });
// setState(() {}); // setState(() {});
}, },
); );
}, },

43
lib/community/community_course.dart

@ -14,6 +14,7 @@ import 'package:huixiang/data/page.dart';
import 'package:huixiang/main.dart'; import 'package:huixiang/main.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
@ -57,32 +58,26 @@ class _CommunityCourse extends State<CommunityCourse>
setState(() {}); setState(() {});
} }
}); });
if (apiService == null) { apiService ??= ApiService(
SharedPreferences.getInstance().then((value) { Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString("token"), _onRefresh();
);
_onRefresh();
});
}
} }
///banner ///banner
queryCourseBanner() async { queryCourseBanner() async {
if (apiService == null) { apiService ??= ApiService(
SharedPreferences value = await SharedPreferences.getInstance(); Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString("token"),
);
}
BaseData<PageInfo<BannerData>>? baseData = await apiService?.queryBanner({ BaseData<PageInfo<BannerData>>? baseData = await apiService?.queryBanner({
"model": {"type": "COURSE_BANNER"}, "model": {"type": "COURSE_BANNER"},
}).catchError((onError) { }).catchError((onError) {
refreshController.refreshFailed(); refreshController.refreshFailed();
return BaseData<PageInfo<BannerData>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
bannerData.clear(); bannerData.clear();
@ -122,6 +117,7 @@ class _CommunityCourse extends State<CommunityCourse>
refreshController.refreshFailed(); refreshController.refreshFailed();
refreshController.loadFailed(); refreshController.loadFailed();
} }
return BaseData<PageInfo<Course>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
if (categoryId == "") { if (categoryId == "") {
@ -144,8 +140,10 @@ class _CommunityCourse extends State<CommunityCourse>
/// ///
collectionList() async { collectionList() async {
BaseListData<CollectClass>? baseData = BaseListData<CollectClass>? baseData = await apiService?.collectList()
await apiService?.collectList().catchError((onError) {}); .catchError((onError) {
return BaseListData<CollectClass>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
collectList.clear(); collectList.clear();
@ -160,8 +158,9 @@ class _CommunityCourse extends State<CommunityCourse>
/// ///
collectCourse(collectId) async { collectCourse(collectId) async {
BaseListData<Course>? baseData = BaseListData<Course>? baseData = await apiService?.collect(collectId).catchError((error) {
await apiService?.collect(collectId).catchError((error) {}); return BaseListData<Course>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
if (!collectMap.containsKey(collectId)) { if (!collectMap.containsKey(collectId)) {

51
lib/community/community_details.dart

@ -1,5 +1,6 @@
import 'dart:ui'; import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.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/data/page.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/retrofit_api.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_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/tips_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/comment_list.dart';
import 'package:huixiang/web/web_view/input_comment.dart'; import 'package:huixiang/web/web_view/input_comment.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../view_widget/classic_header.dart';
import '../view_widget/my_footer.dart';
class CommunityDetails extends StatefulWidget { class CommunityDetails extends StatefulWidget {
final Map<String, dynamic> arguments; final Map<String, dynamic> arguments;
@ -113,6 +115,11 @@ class _CommunityDetails extends State<CommunityDetails>
emojiShowing = false; emojiShowing = false;
}); });
}); });
apiService = ApiService(
Dio(),
context: context,
token: SharedInstance.instance.token,
);
_queryMemberCommentList(true); _queryMemberCommentList(true);
queryDetails(businessId); queryDetails(businessId);
} }
@ -153,11 +160,10 @@ class _CommunityDetails extends State<CommunityDetails>
/// ///
queryDetails(id) async { queryDetails(id) async {
SharedPreferences value = await SharedPreferences.getInstance(); BaseData<Article>? baseData = await apiService?.informationInfo(id).catchError((onError) {
BaseData<Article>? baseData =
await apiService?.informationInfo(id).catchError((onError) {
debugPrint(onError.toString()); debugPrint(onError.toString());
refreshController.refreshFailed(); refreshController.refreshFailed();
return BaseData<Article>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
@ -233,9 +239,7 @@ class _CommunityDetails extends State<CommunityDetails>
exitFull: () { exitFull: () {
setState(() {}); setState(() {});
}, },
userId: widget.arguments != null userId: widget.arguments["userId"] ?? widget.arguments["mid"],
? widget.arguments["userId"]
: widget.arguments["mid"],
itemCount: 3, itemCount: 3,
isDetails: true, isDetails: true,
heightFun: (height) { heightFun: (height) {
@ -308,9 +312,10 @@ class _CommunityDetails extends State<CommunityDetails>
//// ////
_queryInformationLikes() async { _queryInformationLikes() async {
BaseData? baseData = await apiService BaseData? baseData = await apiService?.informationLikes("${businessId}")
?.informationLikes("${businessId}") .catchError((onError) {
.catchError((onError) {}); return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
commentKey.currentState?.setState(() {}); commentKey.currentState?.setState(() {});
setState(() { setState(() {
@ -321,8 +326,6 @@ class _CommunityDetails extends State<CommunityDetails>
article?.likes = likes + 1; article?.likes = likes + 1;
article?.liked = !(article?.liked ?? false); article?.liked = !(article?.liked ?? false);
}); });
} else {
// SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
} }
} }
@ -333,7 +336,9 @@ class _CommunityDetails extends State<CommunityDetails>
"parentId": parenId, "parentId": parenId,
"relationalId": businessId, "relationalId": businessId,
"relationalType": 4 "relationalType": 4
}).catchError((error) {}); }).catchError((error) {
return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
CommentListState? state = commentKey.currentState as CommentListState?; CommentListState? state = commentKey.currentState as CommentListState?;
state?.queryMemberCommentList(); state?.queryMemberCommentList();
@ -346,8 +351,7 @@ class _CommunityDetails extends State<CommunityDetails>
/// ///
_toComment() { _toComment() {
if (commentKey.currentContext == null) return; if (commentKey.currentContext == null) return;
RenderBox? firstRenderBox = RenderBox? firstRenderBox = commentKey.currentContext?.findRenderObject() as RenderBox?;
commentKey.currentContext?.findRenderObject() as RenderBox?;
Offset? first = firstRenderBox?.localToGlobal(Offset.zero); Offset? first = firstRenderBox?.localToGlobal(Offset.zero);
scrollController.animateTo( scrollController.animateTo(
(first?.dy ?? 0) + (first?.dy ?? 0) +
@ -373,7 +377,9 @@ class _CommunityDetails extends State<CommunityDetails>
SmartDialog.show( SmartDialog.show(
builder: (ctx) => Tips(() { builder: (ctx) => Tips(() {
delComment(memberComment); delComment(memberComment);
})); },
),
);
} }
/// ///
@ -398,17 +404,18 @@ class _CommunityDetails extends State<CommunityDetails>
SmartDialog.showLoading( SmartDialog.showLoading(
msg: S.current.zhengzaijiazai, msg: S.current.zhengzaijiazai,
); );
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
BaseData<PageInfo<MemberComment>>? baseData = BaseData<PageInfo<MemberComment>>? baseData = await apiService?.memberCommentList({
await apiService?.memberCommentList({
"pageNum": 1, "pageNum": 1,
"pageSize": 100, "pageSize": 100,
"relationalId": businessId, "relationalId": businessId,
"relationalType": 4, "relationalType": 4,
}).catchError((error) {}); }).catchError((error) {
return BaseData<PageInfo<MemberComment>>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
commentTotal = baseData!.data?.size; commentTotal = baseData!.data?.size;
memberList = baseData!.data?.list ?? []; memberList = baseData.data?.list ?? [];
contentHeight(); contentHeight();
if (mounted) setState(() {}); if (mounted) setState(() {});
SmartDialog.dismiss(); SmartDialog.dismiss();

12
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/data/comunity_comment.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/border_text.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/icon_text.dart'; import 'package:huixiang/view_widget/icon_text.dart';
@ -38,11 +39,8 @@ class _CommunityList extends State<CommunityList> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(Dio(),
if(apiService != null) context: context, token: SharedInstance.instance.token);
apiService = ApiService(Dio(),
context: context, token: value.getString("token")),
});
} }
//// ////
@ -53,8 +51,6 @@ class _CommunityList extends State<CommunityList> {
SmartDialog.showToast(isFollow ? "关注成功" : "取关成功", SmartDialog.showToast(isFollow ? "关注成功" : "取关成功",
alignment: Alignment.center); alignment: Alignment.center);
setState(() {}); setState(() {});
} else {
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center);
} }
} }
@ -65,8 +61,6 @@ class _CommunityList extends State<CommunityList> {
widget.exitFull?.call(); widget.exitFull?.call();
SmartDialog.showToast("删除成功", alignment: Alignment.center); SmartDialog.showToast("删除成功", alignment: Alignment.center);
setState(() {}); setState(() {});
} else {
// SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
} }
} }

33
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/generated/l10n.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/view_widget/tips_dialog.dart';
import 'package:huixiang/web/web_view/comment_list.dart'; import 'package:huixiang/web/web_view/comment_list.dart';
import 'package:huixiang/web/web_view/input_comment.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_interface.dart';
import 'package:sharesdk_plugin/sharesdk_map.dart'; import 'package:sharesdk_plugin/sharesdk_map.dart';
import '../../view_widget/share_dialog.dart';
class ClassDetails extends StatefulWidget { class ClassDetails extends StatefulWidget {
final Map<String, dynamic> arguments; final Map<String, dynamic> arguments;
@ -62,23 +63,18 @@ class _ClassDetails extends State<ClassDetails> with WidgetsBindingObserver {
super.initState(); super.initState();
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
commentFocus.addListener(_focusNodeListener); commentFocus.addListener(_focusNodeListener);
if (apiService == null) { apiService ??= ApiService(
SharedPreferences.getInstance().then((value) { Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString("token"), courseDetails(widget.arguments["id"]);
); queryChapterList(widget.arguments["id"]);
courseDetails(widget.arguments["id"]);
queryChapterList(widget.arguments["id"]);
});
}
} }
/// ///
queryChapterList(courseId) async { queryChapterList(courseId) async {
BaseListData<Chapter>? baseData = BaseListData<Chapter>? baseData = await apiService?.catalogList(courseId).catchError((onError) {
await apiService?.catalogList(courseId).catchError((onError) {
return BaseListData<Chapter>()..isSuccess = false; return BaseListData<Chapter>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -86,8 +82,7 @@ class _ClassDetails extends State<ClassDetails> with WidgetsBindingObserver {
chapterList.clear(); chapterList.clear();
chapterList.addAll(baseData!.data ?? []); chapterList.addAll(baseData!.data ?? []);
chapterIndex = 0; chapterIndex = 0;
ClassDetailsVideoState? state = ClassDetailsVideoState? state = videoKey.currentState as ClassDetailsVideoState?;
videoKey.currentState as ClassDetailsVideoState?;
state?.initVideo(chapterList[chapterIndex].content?.fileUrl); state?.initVideo(chapterList[chapterIndex].content?.fileUrl);
// initVideo(chapterList[chapterIndex].content.fileUrl); // initVideo(chapterList[chapterIndex].content.fileUrl);
}); });
@ -97,8 +92,10 @@ class _ClassDetails extends State<ClassDetails> with WidgetsBindingObserver {
/// ///
courseDetails(id) async { courseDetails(id) async {
BaseData<CourseDetails>? baseData = BaseData<CourseDetails>? baseData = await apiService?.course(id)
await apiService?.course(id).catchError((error) {}); .catchError((error) {
return BaseData<CourseDetails>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
course = baseData!.data; course = baseData!.data;

364
lib/community/community_view/community_dynamic.dart

@ -1,14 +1,17 @@
import 'dart:convert'; import 'dart:convert';
import 'package:chewie/chewie.dart'; import 'package:chewie/chewie.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/data/article.dart'; import 'package:huixiang/data/article.dart';
import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/base_data.dart';
import 'package:chewie/src/chewie_progress_colors.dart' as chewie; import 'package:chewie/src/chewie_progress_colors.dart' as chewie;
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/border_text.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/round_button.dart'; import 'package:huixiang/view_widget/round_button.dart';
@ -35,7 +38,7 @@ class CommunityDynamic extends StatefulWidget {
CommunityDynamic( CommunityDynamic(
this.article, this.article,
this.commentType, { this.commentType, {
Key? key, super.key,
this.itemCount = 9, this.itemCount = 9,
this.heightFun, this.heightFun,
this.isDetails = false, this.isDetails = false,
@ -43,7 +46,7 @@ class CommunityDynamic extends StatefulWidget {
this.exitFull, this.exitFull,
this.userId, this.userId,
this.isList = false, this.isList = false,
}) : super(key: key); });
@override @override
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
@ -56,13 +59,17 @@ class _CommunityDynamic extends State<CommunityDynamic> {
double height = 0; double height = 0;
ApiService? apiService; ApiService? apiService;
late VideoPlayerController videoPlayerController; VideoPlayerController? videoPlayerController;
late ChewieController chewieAudioController; ChewieController? chewieAudioController;
late Chewie chewies; late Chewie chewies;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
apiService = ApiService(Dio(),
context: context,
token: SharedInstance.instance.token,
);
initVideo(); initVideo();
} }
@ -78,10 +85,11 @@ class _CommunityDynamic extends State<CommunityDynamic> {
} else { } else {
videoPlayerController = VideoPlayerController.networkUrl( videoPlayerController = VideoPlayerController.networkUrl(
Uri.parse(cnt["video"]), Uri.parse(cnt["video"]),
)..initialize().then((value) { );
videoPlayerController!.initialize().then((value) {
chewieAudioController = ChewieController( chewieAudioController = ChewieController(
videoPlayerController: videoPlayerController, videoPlayerController: videoPlayerController!,
aspectRatio: videoPlayerController.value.aspectRatio, aspectRatio: videoPlayerController!.value.aspectRatio,
// //
autoPlay: false, autoPlay: false,
// //
@ -97,7 +105,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
), ),
autoInitialize: true, autoInitialize: true,
); );
chewieAudioController.addListener(_fullScreenListener); chewieAudioController!.addListener(_fullScreenListener);
if (mounted) setState(() {}); if (mounted) setState(() {});
}); });
} }
@ -106,34 +114,36 @@ class _CommunityDynamic extends State<CommunityDynamic> {
//// ////
_vipFollow(followId, isFollow) async { _vipFollow(followId, isFollow) async {
BaseData? baseData = await apiService?.follow(followId ?? ""); BaseData? baseData = await apiService?.follow(followId ?? "").catchError((onError) {
return BaseData<dynamic>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
widget.exitFull?.call(); widget.exitFull?.call();
SmartDialog.showToast(isFollow ? "关注成功" : "取关成功", SmartDialog.showToast(
alignment: Alignment.center); isFollow ? "关注成功" : "取关成功",
alignment: Alignment.center,
);
setState(() {}); setState(() {});
} else {
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center);
} }
} }
/// ///
_deleteDynamic(id) async { _deleteDynamic(id) async {
BaseData? baseData = await apiService?.deleteTrend(id); BaseData? baseData = await apiService?.deleteTrend(id).catchError((onError) {
return BaseData<dynamic>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
widget.removalDynamic?.call();
widget.exitFull?.call(); widget.exitFull?.call();
SmartDialog.showToast("删除成功", alignment: Alignment.center); SmartDialog.showToast("删除成功", alignment: Alignment.center);
setState(() {});
} else {
// SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
} }
} }
//// ////
_queryInformationLikes(isLikes) async { _queryInformationLikes(isLikes) async {
BaseData? baseData = await apiService BaseData<dynamic>? baseData = await apiService?.informationLikes("${widget.article?.id}").catchError((onError) {
?.informationLikes("${widget.article?.id}") return BaseData<dynamic>()..isSuccess = false;
.catchError((onError) {}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
widget.exitFull?.call(); widget.exitFull?.call();
setState(() {}); setState(() {});
@ -141,11 +151,15 @@ class _CommunityDynamic extends State<CommunityDynamic> {
} }
goPersonalPage() async { goPersonalPage() async {
await Navigator.of(context).pushNamed('/router/personal_page', arguments: { if (widget.article?.author == null || widget.article?.author == widget.userId) {
"memberId": (widget.article?.author == widget.userId) return;
? "0" }
: widget.article?.author, await Navigator.of(context).pushNamed(
}); '/router/personal_page',
arguments: {
"memberId": widget.article?.author,
},
);
widget.exitFull?.call(); widget.exitFull?.call();
} }
@ -159,7 +173,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
alignment: Alignment.topCenter, alignment: Alignment.topCenter,
padding: EdgeInsets.only( padding: EdgeInsets.only(
left: 16.w, left: 16.w,
top: 16.h, top: 16,
right: 16.w, right: 16.w,
), ),
decoration: BoxDecoration( decoration: BoxDecoration(
@ -188,16 +202,6 @@ class _CommunityDynamic extends State<CommunityDynamic> {
children: [ children: [
GestureDetector( GestureDetector(
onTap: () { 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(); goPersonalPage();
}, },
child: MImage( child: MImage(
@ -220,10 +224,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
Text( Text(
widget.article?.authorName ?? "", widget.article?.authorName ?? "",
style: TextStyle( style: TextStyle(
fontSize: fontSize: 15.sp,
MediaQuery.of(context).size.width >= 650
? 12.sp
: 15.sp,
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: Color(0xFF1A1A1A), color: Color(0xFF1A1A1A),
), ),
@ -231,10 +232,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
Text( Text(
widget.article?.createTime ?? "", widget.article?.createTime ?? "",
style: TextStyle( style: TextStyle(
fontSize: fontSize: 13.sp,
MediaQuery.of(context).size.width >= 650
? 10.sp
: 13.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Color(0xFF808080), color: Color(0xFF808080),
), ),
@ -261,11 +259,10 @@ class _CommunityDynamic extends State<CommunityDynamic> {
}, },
child: (widget.commentType == 0) child: (widget.commentType == 0)
? Container( ? Container(
width: 56.w,
height: 25.h, height: 25.h,
alignment: Alignment.center, alignment: Alignment.center,
child: RoundButton( child: RoundButton(
height: 25.h, height: 28,
backgroup: (widget.article?.followed ?? false) backgroup: (widget.article?.followed ?? false)
? Color(0xFFE6E6E6) ? Color(0xFFE6E6E6)
: Color(0xFF32A060), : Color(0xFF32A060),
@ -276,6 +273,9 @@ class _CommunityDynamic extends State<CommunityDynamic> {
? S.of(context).yiguanzhu ? S.of(context).yiguanzhu
: S.of(context).guanzhu, : S.of(context).guanzhu,
radius: 20, radius: 20,
padding: EdgeInsets.symmetric(
horizontal: 10,
),
icons: Icon( icons: Icon(
(widget.article?.followed ?? false) (widget.article?.followed ?? false)
? Icons.check ? Icons.check
@ -285,7 +285,8 @@ class _CommunityDynamic extends State<CommunityDynamic> {
: Colors.white, : Colors.white,
size: 15, size: 15,
), ),
)) ),
)
: Padding( : Padding(
padding: EdgeInsets.all(20), padding: EdgeInsets.all(20),
child: Icon( child: Icon(
@ -302,7 +303,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
), ),
widget.isList widget.isList
? Text( ? Text(
widget.article?.mainTitle ?? "", widget.article?.mainTitle?.trim() ?? "",
maxLines: 5, maxLines: 5,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: TextStyle( style: TextStyle(
@ -312,7 +313,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
), ),
) )
: Text( : Text(
widget.article?.mainTitle ?? "", widget.article?.mainTitle?.trim() ?? "",
style: TextStyle( style: TextStyle(
color: Color(0xFF1A1A1A), color: Color(0xFF1A1A1A),
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
@ -325,7 +326,10 @@ class _CommunityDynamic extends State<CommunityDynamic> {
), ),
if (widget.article?.location != "") if (widget.article?.location != "")
Padding( Padding(
padding: EdgeInsets.only(bottom: 7), padding: EdgeInsets.only(
top: 7,
bottom: widget.isList ? 0 : 12,
),
child: Row( child: Row(
children: [ children: [
Icon( Icon(
@ -357,18 +361,39 @@ class _CommunityDynamic extends State<CommunityDynamic> {
), ),
if (!widget.isDetails) if (!widget.isDetails)
Container( Container(
// padding: EdgeInsets.only(bottom: 16), padding: EdgeInsets.only(bottom: 12),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
Expanded( Expanded(
child: Container( child: Row(
padding: EdgeInsets.only(bottom: 16.h), 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( child: Row(
children: [ children: [
SvgPicture.asset( SvgPicture.asset(
"assets/svg/liulanliang.svg", "assets/svg/pinglun.svg",
width: 16, width: 16,
height: 16, height: 16,
), ),
@ -376,7 +401,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
width: 5.w, width: 5.w,
), ),
Text( Text(
"${widget.article?.viewers}", "${widget.article?.comments ?? 0}",
style: TextStyle( style: TextStyle(
fontSize: 14.sp, fontSize: 14.sp,
fontFamily: 'JDZhengHT', fontFamily: 'JDZhengHT',
@ -386,32 +411,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
), ),
], ],
), ),
),
), ),
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( Expanded(
child: GestureDetector( child: GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
@ -423,40 +423,36 @@ class _CommunityDynamic extends State<CommunityDynamic> {
widget.article?.liked ?? false); widget.article?.liked ?? false);
}); });
}, },
child: Container( child: Row(
padding: EdgeInsets.only(bottom: 16.h), children: [
child: Row( (widget.article?.liked ?? false)
children: [ ? Image.asset(
(widget.article?.liked ?? false) "assets/image/icon_like.webp",
? Image.asset( width: 16,
"assets/image/icon_like.webp", height: 16,
width: 16, )
height: 16, : Image.asset(
) "assets/image/icon_like_h.webp",
: Image.asset( width: 16,
"assets/image/icon_like_h.webp", height: 16,
width: 16, ),
height: 16, SizedBox(
), width: 5.w,
SizedBox( ),
width: 5.w, Text(
), "${widget.article?.likes ?? 0}",
Text( style: TextStyle(
"${widget.article?.likes ?? 0}", fontSize: 14.sp,
style: TextStyle( fontFamily: 'JDZhengHT',
fontSize: 14.sp, fontWeight: MyFontWeight.regular,
fontFamily: 'JDZhengHT', color: Color(0xFF1A1A1A),
fontWeight: MyFontWeight.regular,
color: Color(0xFF1A1A1A),
),
), ),
], ),
), ],
), ),
), ),
), ),
if ((widget.article?.author != (widget.userId ?? "")) && if (widget.commentType == 0)
widget.commentType == 0)
Expanded( Expanded(
child: GestureDetector( child: GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
@ -468,9 +464,8 @@ class _CommunityDynamic extends State<CommunityDynamic> {
child: Container( child: Container(
padding: EdgeInsets.only( padding: EdgeInsets.only(
top: 3.h, top: 3.h,
bottom: 16.h,
), ),
alignment: Alignment.center, alignment: Alignment.centerRight,
// color: Colors.red, // color: Colors.red,
child: Icon( child: Icon(
Icons.more_horiz, Icons.more_horiz,
@ -486,7 +481,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
), ),
), ),
Container( Container(
height: 16.h, height: 16,
color: Color(0xFFF7F7F7), color: Color(0xFFF7F7F7),
), ),
], ],
@ -534,7 +529,8 @@ class _CommunityDynamic extends State<CommunityDynamic> {
print("share!$state"); print("share!$state");
}); });
}); });
}); },
);
} }
String buildShareUrl() { String buildShareUrl() {
@ -552,38 +548,37 @@ class _CommunityDynamic extends State<CommunityDynamic> {
cnt["images"] != null && cnt["images"] != null &&
cnt["images"].length > 0) { cnt["images"].length > 0) {
if (cnt["images"].length == 1) { if (cnt["images"].length == 1) {
itemWidget = Container( itemWidget = InkWell(
child: InkWell( onTap: () {
onTap: () { // ImagePickers.previewImages(subjectInfo.images,0);
// ImagePickers.previewImages(subjectInfo.images,0); Navigator.push(
Navigator.push( context,
context, MaterialPageRoute(
MaterialPageRoute( builder: (context) => PhotoViewGalleryScreen(
builder: (context) => PhotoViewGalleryScreen( images: cnt["images"], //list
images: cnt["images"], //list index: 0, //index
index: 0, //index ),
), ),
), );
); },
}, child: Container(
child: MImage( constraints: BoxConstraints(
cnt["images"][0], maxHeight: MediaQuery.of(context).size.width / 1.5,
fit: BoxFit.contain, ),
radius: BorderRadius.circular(2), child: MImage(
height: MediaQuery.of(context).size.width / 1.5, cnt["images"][0],
errorSrc: "assets/image/default_2_1.webp", radius: BorderRadius.circular(2),
fadeSrc: "assets/image/default_2_1.webp", errorSrc: "assets/image/default_2_1.webp",
)), fadeSrc: "assets/image/default_2_1.webp",
),
),
); );
} else { } else {
itemWidget = GridView.builder( itemWidget = GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount: (cnt["images"].length == 2 || cnt["images"].length == 4) ? 2 : 3,
(cnt["images"].length == 2 || cnt["images"].length == 4) crossAxisSpacing: 12,
? 2 mainAxisSpacing: 12,
: 3,
crossAxisSpacing: 12.w,
mainAxisSpacing: 12.w,
childAspectRatio: 1, childAspectRatio: 1,
), ),
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
@ -618,14 +613,12 @@ class _CommunityDynamic extends State<CommunityDynamic> {
itemCount: cnt["images"].length, itemCount: cnt["images"].length,
); );
} }
} else if (cnt["type"] == "video" && } else if (cnt["type"] == "video" && cnt["video"] != null && cnt["video"].isNotEmpty) {
cnt["video"] != null &&
cnt["video"].isNotEmpty) {
itemWidget = videoWidget( itemWidget = videoWidget(
MediaQuery.of(context).size.width - 32, MediaQuery.of(context).size.width - 32,
videoPlayerController != null videoPlayerController != null
? (MediaQuery.of(context).size.width - 32) / ? (MediaQuery.of(context).size.width - 32) /
videoPlayerController.value.aspectRatio videoPlayerController!.value.aspectRatio
: MediaQuery.of(context).size.width / 2, : MediaQuery.of(context).size.width / 2,
cnt["video"].replaceAll(".mp4", "_poster.jpg"), cnt["video"].replaceAll(".mp4", "_poster.jpg"),
); );
@ -636,7 +629,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
SizedBox( SizedBox(
height: 16.h, height: 16,
), ),
itemWidget, itemWidget,
], ],
@ -646,11 +639,11 @@ class _CommunityDynamic extends State<CommunityDynamic> {
@override @override
void dispose() { void dispose() {
super.dispose(); super.dispose();
chewieAudioController.pause(); chewieAudioController?.pause();
chewieAudioController.dispose(); chewieAudioController?.dispose();
videoPlayerController.pause(); videoPlayerController?.pause();
videoPlayerController.dispose(); videoPlayerController?.dispose();
} }
Widget videoWidget(double width, double height, src) { Widget videoWidget(double width, double height, src) {
@ -664,7 +657,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
width: width, width: width,
height: height, height: height,
child: chewies = Chewie( child: chewies = Chewie(
controller: chewieAudioController, controller: chewieAudioController!,
), ),
) )
: Container( : Container(
@ -683,7 +676,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
child: MImage( child: MImage(
src, src,
aspectRatio: videoPlayerController != null aspectRatio: videoPlayerController != null
? videoPlayerController.value.aspectRatio ? videoPlayerController!.value.aspectRatio
: (width / 7 * 5), : (width / 7 * 5),
fit: BoxFit.cover, fit: BoxFit.cover,
errorSrc: "assets/image/default_2_1.webp", errorSrc: "assets/image/default_2_1.webp",
@ -704,7 +697,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
} }
Future<void> _fullScreenListener() async { Future<void> _fullScreenListener() async {
if (!chewieAudioController.isFullScreen) { if (!(chewieAudioController?.isFullScreen ?? false)) {
Future.delayed(Duration(seconds: 1), () { Future.delayed(Duration(seconds: 1), () {
widget.exitFull?.call(); widget.exitFull?.call();
}); });
@ -793,19 +786,22 @@ class _CommunityDynamic extends State<CommunityDynamic> {
return buildBottomSheetWidget(context); return buildBottomSheetWidget(context);
}, },
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
context: context); context: context,
);
} }
Widget buildBottomSheetWidget(BuildContext context) { Widget buildBottomSheetWidget(BuildContext context) {
return Container( return Container(
padding: EdgeInsets.all(16), padding: EdgeInsets.all(16),
decoration: new BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: new BorderRadius.only( borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(25.0), topLeft: const Radius.circular(25.0),
topRight: const Radius.circular(25.0))), topRight: const Radius.circular(25.0),
),
),
child: Container( child: Container(
height: 130.h, height: ("${widget.article?.author ?? ""}" == "${SharedInstance.instance.userId}") ? 145.h : 100.h,
child: Column( child: Column(
children: [ children: [
GestureDetector( GestureDetector(
@ -845,7 +841,8 @@ class _CommunityDynamic extends State<CommunityDynamic> {
), ),
], ],
), ),
)), ),
),
Container( Container(
margin: EdgeInsets.symmetric(vertical: 12), margin: EdgeInsets.symmetric(vertical: 12),
height: 1.h, height: 1.h,
@ -855,8 +852,7 @@ class _CommunityDynamic extends State<CommunityDynamic> {
behavior: HitTestBehavior.translucent, behavior: HitTestBehavior.translucent,
onTap: () { onTap: () {
setState(() { setState(() {
Navigator.of(context) Navigator.of(context).popAndPushNamed('/router/report_page', arguments: {
.popAndPushNamed('/router/report_page', arguments: {
"userName": widget.article?.authorName ?? "", "userName": widget.article?.authorName ?? "",
"authorId": widget.article?.author ?? "", "authorId": widget.article?.author ?? "",
}); });
@ -889,7 +885,50 @@ class _CommunityDynamic extends State<CommunityDynamic> {
], ],
), ),
), ),
) ),
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<CommunityDynamic> {
widget.heightFun?.call(height); widget.heightFun?.call(height);
print("height: $height"); print("height: $height");
} }
} }

39
lib/community/community_view/course_banner.dart

@ -22,11 +22,10 @@ class CourseBanner extends StatefulWidget {
} }
class _CourseBanner extends State<CourseBanner> { class _CourseBanner extends State<CourseBanner> {
ApiService? apiService;
final RefreshController refreshController = RefreshController(); final RefreshController refreshController = RefreshController();
List<BannerData> bannerData = []; List<BannerData> bannerData = [];
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(
@ -76,20 +75,26 @@ class _CourseBanner extends State<CourseBanner> {
bannerClick(BannerData bannerData) async { bannerClick(BannerData bannerData) async {
switch (bannerData.contentType) { switch (bannerData.contentType) {
case 1: case 1:
Navigator.of(context).pushNamed('/router/integral_store_page', Navigator.of(context).pushNamed(
arguments: {"goodsId": bannerData.content}); '/router/integral_store_page',
arguments: {"goodsId": bannerData.content},
);
break; break;
case 2: case 2:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page',
"activityId": bannerData.content, arguments: {
}); "activityId": bannerData.content,
},
);
break; break;
case 3: case 3:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page',
"articleId": bannerData.content, arguments: {
}); "articleId": bannerData.content,
},
);
break; break;
case 4: case 4:
String? router = bannerData.content; String? router = bannerData.content;
@ -106,10 +111,12 @@ class _CourseBanner extends State<CourseBanner> {
} }
break; break;
case 5: case 5:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/class_details', arguments: { '/router/class_details',
"id": bannerData.content, arguments: {
}); "id": bannerData.content,
},
);
break; break;
case 7: case 7:
String? router = bannerData.content; String? router = bannerData.content;

1
lib/community/community_view/home_class.dart

@ -21,7 +21,6 @@ class HomeClass extends StatefulWidget {
} }
class _HomeClass extends State<HomeClass> { class _HomeClass extends State<HomeClass> {
ApiService? apiService;
Position? latLng; Position? latLng;
final TextEditingController editingController = TextEditingController(); final TextEditingController editingController = TextEditingController();

4
lib/community/headlines/activity_top_list.dart

@ -1,8 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/data/article.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/font_weight.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
@ -19,8 +17,6 @@ class ActivityTopList extends StatefulWidget {
} }
class _ActivityTopList extends State<ActivityTopList> { class _ActivityTopList extends State<ActivityTopList> {
ApiService? apiService;
Position? latLng;
final TextEditingController editingController = TextEditingController(); final TextEditingController editingController = TextEditingController();

32
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/data/article.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/custom_image.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
@ -28,10 +29,10 @@ class _ArticleList extends State<ArticleList> {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(Dio(),
apiService = ApiService(Dio(), context: context,
context: context, token: value.getString("token")), token: SharedInstance.instance.token,
}); );
} }
@override @override
@ -53,7 +54,8 @@ class _ArticleList extends State<ArticleList> {
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: Colors.black, color: Colors.black,
), ),
)), ),
),
ListView.builder( ListView.builder(
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
itemCount: widget.articles.length, itemCount: widget.articles.length,
@ -76,7 +78,8 @@ class _ArticleList extends State<ArticleList> {
}, },
), ),
], ],
)); ),
);
} }
Widget articleItem(Article articles, position) { Widget articleItem(Article articles, position) {
@ -125,21 +128,6 @@ class _ArticleList extends State<ArticleList> {
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ 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( Image.asset(
"assets/image/browse.webp", "assets/image/browse.webp",
width: 14, width: 14,
@ -171,7 +159,7 @@ class _ArticleList extends State<ArticleList> {
), ),
), ),
], ],
) ),
], ],
), ),
), ),

14
lib/community/headlines/article_page.dart

@ -1,3 +1,4 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/store_title_tab.dart'; import 'package:huixiang/view_widget/store_title_tab.dart';
@ -60,6 +62,10 @@ class _ArticlePage extends State<ArticlePage>
setState(() {}); setState(() {});
} }
}); });
apiService = ApiService(Dio(),
context: context,
token: SharedInstance.instance.token,
);
queryArticleList(false); queryArticleList(false);
queryArticleList(true); queryArticleList(true);
queryHeadlinesBanner(); queryHeadlinesBanner();
@ -78,6 +84,7 @@ class _ArticlePage extends State<ArticlePage>
"model": {"type": "INFORMATION"}, "model": {"type": "INFORMATION"},
}).catchError((onError) { }).catchError((onError) {
refreshController.refreshFailed(); refreshController.refreshFailed();
return BaseData<PageInfo<BannerData>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
bannerData.clear(); bannerData.clear();
@ -108,6 +115,7 @@ class _ArticlePage extends State<ArticlePage>
}).catchError((onError) { }).catchError((onError) {
refreshController.refreshFailed(); refreshController.refreshFailed();
refreshController.loadFailed(); refreshController.loadFailed();
return BaseData<PageInfo<Article>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
refreshController.refreshCompleted(); refreshController.refreshCompleted();
@ -139,8 +147,7 @@ class _ArticlePage extends State<ArticlePage>
/// ///
queryHeadlinesList() async { queryHeadlinesList() async {
BaseListData<Headlines>? baseData = BaseListData<Headlines>? baseData = await apiService?.headlinesList().catchError((onError) {
await apiService?.headlinesList().catchError((onError) {
return BaseListData<Headlines>()..isSuccess = false; return BaseListData<Headlines>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -248,7 +255,8 @@ class _ArticlePage extends State<ArticlePage>
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: Colors.black, color: Colors.black,
), ),
)), ),
),
/// ///
HeadlinesCollection(headlines, articles), HeadlinesCollection(headlines, articles),

38
lib/community/headlines/headlines_banner.dart

@ -22,7 +22,7 @@ class HeadlinesBanner extends StatefulWidget {
} }
class _HeadlinesBanner extends State<HeadlinesBanner> { class _HeadlinesBanner extends State<HeadlinesBanner> {
ApiService? apiService;
final RefreshController refreshController = RefreshController(); final RefreshController refreshController = RefreshController();
List<BannerData> bannerData = []; List<BannerData> bannerData = [];
@ -73,20 +73,26 @@ class _HeadlinesBanner extends State<HeadlinesBanner> {
bannerClick(BannerData bannerData) async { bannerClick(BannerData bannerData) async {
switch (bannerData.contentType) { switch (bannerData.contentType) {
case 1: case 1:
Navigator.of(context).pushNamed('/router/integral_store_page', Navigator.of(context).pushNamed(
arguments: {"goodsId": bannerData.content}); '/router/integral_store_page',
arguments: {"goodsId": bannerData.content},
);
break; break;
case 2: case 2:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page',
"activityId": bannerData.content, arguments: {
}); "activityId": bannerData.content,
},
);
break; break;
case 3: case 3:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page',
"articleId": bannerData.content, arguments: {
}); "articleId": bannerData.content,
},
);
break; break;
case 4: case 4:
String? router = bannerData.content; String? router = bannerData.content;
@ -103,10 +109,12 @@ class _HeadlinesBanner extends State<HeadlinesBanner> {
} }
break; break;
case 5: case 5:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/class_details', arguments: { '/router/class_details',
"id": bannerData.content, arguments: {
}); "id": bannerData.content,
},
);
break; break;
case 7: case 7:
String? router = bannerData.content; String? router = bannerData.content;

2
lib/community/headlines/headlines_collection.dart

@ -21,7 +21,7 @@ class HeadlinesCollection extends StatefulWidget {
} }
class _HeadlinesCollection extends State<HeadlinesCollection> { class _HeadlinesCollection extends State<HeadlinesCollection> {
ApiService? apiService;
Position? latLng; Position? latLng;
final TextEditingController editingController = TextEditingController(); final TextEditingController editingController = TextEditingController();

88
lib/community/headlines/headlines_column_details.dart

@ -1,3 +1,4 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:huixiang/data/headlines_details.dart'; import 'package:huixiang/data/headlines_details.dart';
import 'package:huixiang/generated/l10n.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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/utils/font_weight.dart';
import 'package:flutter_screenutil/flutter_screenutil.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
@ -39,13 +41,19 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
void initState() { void initState() {
super.initState(); super.initState();
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
apiService = ApiService(Dio(),
context: context,
token: SharedInstance.instance.token,
);
_onRefresh(); _onRefresh();
} }
/// ///
queryHeadlinesDetails(id) async { queryHeadlinesDetails(id) async {
BaseData<HeadlinesDetails>? baseData = BaseData<HeadlinesDetails>? baseData = await apiService?.headlinesDetails(id)
await apiService?.headlinesDetails(id).catchError((error) {}); .catchError((error) {
return BaseData<HeadlinesDetails>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
headlinesListDetails = baseData!.data; headlinesListDetails = baseData!.data;
@ -66,6 +74,7 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
}).catchError((onError) { }).catchError((onError) {
refreshController.refreshFailed(); refreshController.refreshFailed();
refreshController.loadFailed(); refreshController.loadFailed();
return BaseData<PageInfo<Article>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
refreshController.refreshCompleted(); refreshController.refreshCompleted();
@ -239,10 +248,8 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
child: Column( child: Column(
children: [ children: [
Row( Row(
mainAxisAlignment: mainAxisAlignment: MainAxisAlignment.start,
MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [ children: [
Text( Text(
"简介:", "简介:",
@ -272,7 +279,7 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
color: Colors.black, color: Colors.black,
), ),
), ),
) ),
], ],
), ),
SizedBox(height: 3.h), SizedBox(height: 3.h),
@ -293,8 +300,7 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
S.of(context).gengduo, S.of(context).gengduo,
style: TextStyle( style: TextStyle(
fontSize: 12.sp, fontSize: 12.sp,
fontWeight: fontWeight: MyFontWeight.regular,
MyFontWeight.regular,
color: Colors.black, color: Colors.black,
), ),
), ),
@ -325,10 +331,12 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
itemBuilder: (context, position) { itemBuilder: (context, position) {
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page',
"articleId": articles[position].id arguments: {
}); "articleId": articles[position].id
},
);
int viewers = articles[position].viewers ?? 0; int viewers = articles[position].viewers ?? 0;
articles[position].viewers = (viewers + 1); articles[position].viewers = (viewers + 1);
setState(() {}); setState(() {});
@ -378,8 +386,7 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
children: [ children: [
Expanded( Expanded(
child: Container( child: Container(
height: height: MediaQuery.of(context).size.width >= 650 ? 133.h : 105,
MediaQuery.of(context).size.width >= 650 ? 133.h : 105,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
@ -397,34 +404,22 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
), ),
SizedBox(height: 6.h), SizedBox(height: 6.h),
Expanded( Expanded(
child: Text( child: Text(
articles.viceTitle ?? "", articles.viceTitle ?? "",
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
maxLines: 1, maxLines: 1,
style: TextStyle( style: TextStyle(
fontSize: 12.sp, fontSize: 12.sp,
height: 1.2.h, height: 1.2.h,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Color(0xFF353535), color: Color(0xFF353535),
),
), ),
)), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ 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( Image.asset(
"assets/image/browse.webp", "assets/image/browse.webp",
width: 14, width: 14,
@ -432,14 +427,15 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
color: Color(0xFF808080), color: Color(0xFF808080),
), ),
Expanded( Expanded(
child: Text( child: Text(
"${articles.viewers}" ?? "", "${articles.viewers}" ?? "",
style: TextStyle( style: TextStyle(
fontSize: 12.sp, fontSize: 12.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Color(0xFF8D8D8D), color: Color(0xFF8D8D8D),
),
), ),
)), ),
Expanded( Expanded(
child: Text( child: Text(
articles.createTime?.split(":")[0] ?? "", articles.createTime?.split(":")[0] ?? "",
@ -449,7 +445,7 @@ class _HeadlinesColumnDetails extends State<HeadlinesColumnDetails>
color: Color(0xFF8D8D8D), color: Color(0xFF8D8D8D),
), ),
), ),
) ),
], ],
), ),
], ],

38
lib/community/new_community_details.dart

@ -1,6 +1,7 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:ui'; import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.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/generated/l10n.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/round_button.dart'; import 'package:huixiang/view_widget/round_button.dart';
@ -66,15 +68,15 @@ class _NewCommunityDetails extends State<NewCommunityDetails>
userId = widget.arguments?["userId"]; userId = widget.arguments?["userId"];
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
commentFocus.addListener(_focusNodeListener); commentFocus.addListener(_focusNodeListener);
apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
queryDetails(commentsId); queryDetails(commentsId);
} }
/// ///
queryDetails(id) async { queryDetails(id) async {
SharedPreferences value = await SharedPreferences.getInstance(); BaseData<Article>? baseData = await apiService?.informationInfo(id).catchError((onError) {
BaseData<Article>? baseData =
await apiService?.informationInfo(id).catchError((onError) {
debugPrint(onError.toString()); debugPrint(onError.toString());
return BaseData<Article>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
@ -90,8 +92,6 @@ class _NewCommunityDetails extends State<NewCommunityDetails>
SmartDialog.showToast(isFollow ? "关注成功" : "取关成功", SmartDialog.showToast(isFollow ? "关注成功" : "取关成功",
alignment: Alignment.center); alignment: Alignment.center);
setState(() {}); setState(() {});
} else {
// SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
} }
} }
@ -436,7 +436,8 @@ class _NewCommunityDetails extends State<NewCommunityDetails>
height: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.width,
errorSrc: "assets/image/default_2_1.webp", errorSrc: "assets/image/default_2_1.webp",
fadeSrc: "assets/image/default_2_1.webp", fadeSrc: "assets/image/default_2_1.webp",
)), ),
),
); );
} else { } else {
itemWidget = GridView.builder( itemWidget = GridView.builder(
@ -520,9 +521,10 @@ class _NewCommunityDetails extends State<NewCommunityDetails>
//// ////
_queryInformationLikes() async { _queryInformationLikes() async {
BaseData? baseData = await apiService BaseData? baseData = await apiService?.informationLikes("${commentsId}")
?.informationLikes("${commentsId}") .catchError((onError) {
.catchError((onError) {}); return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
commentKey.currentState?.setState(() {}); commentKey.currentState?.setState(() {});
setState(() { setState(() {
@ -533,8 +535,6 @@ class _NewCommunityDetails extends State<NewCommunityDetails>
article?.likes = likes + 1; article?.likes = likes + 1;
article?.liked = !(article?.liked ?? false); article?.liked = !(article?.liked ?? false);
}); });
} else {
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center);
} }
} }
@ -545,7 +545,9 @@ class _NewCommunityDetails extends State<NewCommunityDetails>
"parentId": parenId, "parentId": parenId,
"relationalId": commentsId, "relationalId": commentsId,
"relationalType": 4 "relationalType": 4
}).catchError((error) {}); }).catchError((error) {
return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
CommentListState? state = commentKey.currentState as CommentListState?; CommentListState? state = commentKey.currentState as CommentListState?;
state?.queryMemberCommentList(); state?.queryMemberCommentList();
@ -585,7 +587,9 @@ class _NewCommunityDetails extends State<NewCommunityDetails>
SmartDialog.show( SmartDialog.show(
builder: (ctx) => Tips(() { builder: (ctx) => Tips(() {
delComment(memberComment); delComment(memberComment);
})); },
),
);
} }
/// ///
@ -606,14 +610,14 @@ class _NewCommunityDetails extends State<NewCommunityDetails>
/// ///
_queryMemberCommentList() async { _queryMemberCommentList() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); BaseData<PageInfo<MemberComment>>? baseData = await apiService?.memberCommentList({
BaseData<PageInfo<MemberComment>>? baseData =
await apiService?.memberCommentList({
"pageNum": 1, "pageNum": 1,
"pageSize": 100, "pageSize": 100,
"relationalId": commentsId, "relationalId": commentsId,
"relationalType": 4, "relationalType": 4,
}).catchError((error) {}); }).catchError((error) {
return BaseData<PageInfo<MemberComment>>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
commentTotal = baseData?.data?.size; commentTotal = baseData?.data?.size;
memberList = baseData?.data?.list ?? []; memberList = baseData?.data?.list ?? [];

1
lib/community/order_page.dart

@ -29,6 +29,7 @@ class _OrderPage extends State<OrderPage> with SingleTickerProviderStateMixin,Au
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
return DefaultTabController( return DefaultTabController(
length: 4, length: 4,
child: Scaffold( child: Scaffold(

7
lib/community/photo_view_gallery_screen.dart

@ -21,18 +21,19 @@ class PhotoViewGalleryScreen extends StatefulWidget {
} }
class _PhotoViewGalleryScreenState extends State<PhotoViewGalleryScreen> { class _PhotoViewGalleryScreenState extends State<PhotoViewGalleryScreen> {
int currentIndex=0; int currentIndex = 0;
@override @override
void initState() { void initState() {
// TODO: implement initState currentIndex = widget.index;
super.initState(); super.initState();
currentIndex=widget.index;
} }
File fileFromDocsDir(String filename) { File fileFromDocsDir(String filename) {
String pathName = p.join(ImgCachePath.instance.path, filename); String pathName = p.join(ImgCachePath.instance.path, filename);
return File(pathName); return File(pathName);
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(

27
lib/community/release_dynamic.dart

@ -8,6 +8,7 @@ import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/data/address.dart'; import 'package:huixiang/data/address.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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_appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_pickers/image_pickers.dart'; import 'package:image_pickers/image_pickers.dart';
@ -38,14 +39,12 @@ class _ReleaseDynamic extends State<ReleaseDynamic> {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) { apiService = ApiService(
apiService = ApiService( Dio(),
Dio(), context: context,
context: context, token: SharedInstance.instance.token,
token: value.getString("token"), showLoading: false,
showLoading: false, );
);
});
} }
@override @override
@ -238,7 +237,8 @@ class _ReleaseDynamic extends State<ReleaseDynamic> {
isDestructiveAction: true, isDestructiveAction: true,
), ),
); );
}); },
);
} }
/// ///
@ -272,7 +272,8 @@ class _ReleaseDynamic extends State<ReleaseDynamic> {
isDestructiveAction: true, isDestructiveAction: true,
), ),
); );
}); },
);
} }
Widget addImageItem() { Widget addImageItem() {
@ -440,7 +441,8 @@ class _ReleaseDynamic extends State<ReleaseDynamic> {
), ),
], ],
), ),
)), ),
),
addressController.text == "" addressController.text == ""
? Container() ? Container()
: GestureDetector( : GestureDetector(
@ -469,7 +471,8 @@ class _ReleaseDynamic extends State<ReleaseDynamic> {
height: 5, height: 5,
) )
], ],
)); ),
);
} }
} }

6
lib/community/report/report_notice.dart

@ -14,7 +14,7 @@ class ReportNotice extends StatefulWidget {
} }
class _ReportNotice extends State<ReportNotice> { class _ReportNotice extends State<ReportNotice> {
ApiService? apiService;
int checkIndex = 0; int checkIndex = 0;
@override @override
@ -35,7 +35,9 @@ class _ReportNotice extends State<ReportNotice> {
body: Container( body: Container(
width: double.infinity, width: double.infinity,
color: Color(0xFFFFFFFFF), color: Color(0xFFFFFFFFF),
padding: EdgeInsets.only(left: 16, top: 10, right: 16), padding: EdgeInsets.only(
left: 16, top: 10, right: 16,
),
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,

290
lib/community/report/report_page.dart

@ -1,10 +1,11 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/base_data.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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_appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
@ -32,13 +33,20 @@ class _ReportPage extends State<ReportPage> {
super.initState(); super.initState();
userName = widget.arguments?['userName']; userName = widget.arguments?['userName'];
authorId = widget.arguments?['authorId']; authorId = widget.arguments?['authorId'];
apiService = ApiService(
Dio(),
context: context,
token: SharedInstance.instance.token,
);
} }
report() async { report() async {
BaseData? baseData = await apiService?.complaint({ BaseData? baseData = await apiService?.complaint({
"content": checkIndex == 9 ? editingController.text : textCon, "content": checkIndex == 9 ? editingController.text : textCon,
"informationId": authorId, "informationId": authorId,
}).catchError((onError) {}); }).catchError((onError) {
return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
Navigator.of(context).popAndPushNamed('/router/report_success'); Navigator.of(context).popAndPushNamed('/router/report_success');
} else { } else {
@ -70,12 +78,16 @@ class _ReportPage extends State<ReportPage> {
Container( Container(
width: double.infinity, width: double.infinity,
color: Color(0XFFFFFFFF), color: Color(0XFFFFFFFF),
padding: EdgeInsets.only(bottom: 4, left: 16, right: 16), padding: EdgeInsets.only(
bottom: 4,
left: 16,
right: 16,
),
child: Text.rich( child: Text.rich(
TextSpan( TextSpan(
children: [ children: [
TextSpan( TextSpan(
text:S.of(context).jubao, text: S.of(context).jubao,
style: TextStyle( style: TextStyle(
fontSize: 16.sp, fontSize: 16.sp,
fontWeight: MyFontWeight.medium, fontWeight: MyFontWeight.medium,
@ -106,70 +118,78 @@ class _ReportPage extends State<ReportPage> {
SizedBox(height: 12), SizedBox(height: 12),
if (checkIndex == 9) if (checkIndex == 9)
Container( Container(
width: double.infinity, width: double.infinity,
height: 186.h, height: 186.h,
margin: margin: EdgeInsets.only(
EdgeInsets.only(right: 16, left: 40, bottom: 100), right: 16,
decoration: new BoxDecoration( left: 40,
color: Color(0xFFF7F7F7), bottom: 100,
borderRadius: BorderRadius.circular(4.0), ),
), decoration: new BoxDecoration(
child: Container( color: Color(0xFFF7F7F7),
margin: EdgeInsets.fromLTRB(20.w, 5.h, 20.w, 0), borderRadius: BorderRadius.circular(4.0),
alignment: Alignment.topLeft, ),
child: TextField( child: Container(
maxLines: 5, margin: EdgeInsets.fromLTRB(20.w, 5.h, 20.w, 0),
controller: editingController, alignment: Alignment.topLeft,
onChanged: (value) { child: TextField(
setState(() { maxLines: 5,
textLength = value.length; controller: editingController,
}); onChanged: (value) {
}, setState(() {
maxLength: 100, textLength = value.length;
decoration: InputDecoration( });
border: InputBorder.none, },
hintText: S.of(context).jubaoyuanyin, maxLength: 100,
hintStyle: TextStyle( decoration: InputDecoration(
fontSize: 12.sp, border: InputBorder.none,
height: 1.2, hintText: S.of(context).jubaoyuanyin,
fontWeight: MyFontWeight.regular, hintStyle: TextStyle(
color: Color(0xFF999999), fontSize: 12.sp,
), height: 1.2,
fontWeight: MyFontWeight.regular,
color: Color(0xFF999999),
), ),
), ),
)) ),
),
)
], ],
), ),
), ),
Align( Align(
alignment: Alignment.bottomCenter, alignment: Alignment.bottomCenter,
child: Container( child: Container(
width: double.infinity, width: double.infinity,
height: 95, height: 95,
child: Column( child: Column(
children: [ children: [
GestureDetector( GestureDetector(
onTap: () { onTap: () {
Navigator.of(context) Navigator.of(context)
.pushNamed('/router/report_notice'); .pushNamed('/router/report_notice');
}, },
child: Container( child: Container(
alignment: Alignment.bottomCenter, alignment: Alignment.bottomCenter,
margin: EdgeInsets.only(bottom: 25), margin: EdgeInsets.only(bottom: 25),
child: Text( child: Text(
S.of(context).toushuxuzhi, S.of(context).toushuxuzhi,
style: TextStyle( style: TextStyle(
fontSize: 14.sp, fontSize: 14.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Color(0xFF3C425C), color: Color(0xFF3C425C),
), ),
), ),
)), ),
Expanded( ),
child: GestureDetector( Expanded(
child: GestureDetector(
onTap: () { onTap: () {
if(checkIndex == 9 && editingController.text == ""){ if (checkIndex == 9 && editingController.text == "") {
SmartDialog.showToast("请输入举报原因", alignment: Alignment.center); SmartDialog.showToast(
"请输入举报原因",
alignment: Alignment.center,
);
return; return;
} }
report(); report();
@ -191,10 +211,12 @@ class _ReportPage extends State<ReportPage> {
), ),
), ),
), ),
)) ),
], ),
), ],
)) ),
),
),
], ],
), ),
), ),
@ -203,45 +225,50 @@ class _ReportPage extends State<ReportPage> {
Widget reportContent() { Widget reportContent() {
return Container( return Container(
width: double.infinity, width: double.infinity,
padding: EdgeInsets.only(left: 16, right: 16, top: 20), padding: EdgeInsets.only(
child: Column( left: 16,
children: [ right: 16,
content("色情低俗", 1), top: 20,
SizedBox( ),
height: 18, child: Column(
), children: [
content("政治宗教", 2), content("色情低俗", 1),
SizedBox( SizedBox(
height: 18, height: 18,
), ),
content("广告骚扰", 3), content("政治宗教", 2),
SizedBox( SizedBox(
height: 18, height: 18,
), ),
content("虚假欺骗", 4), content("广告骚扰", 3),
SizedBox( SizedBox(
height: 18, height: 18,
), ),
content("侵权(诽谤、抄袭、冒用)", 5), content("虚假欺骗", 4),
SizedBox( SizedBox(
height: 18, height: 18,
), ),
content("不良封面/标题", 6), content("侵权(诽谤、抄袭、冒用)", 5),
SizedBox( SizedBox(
height: 18, height: 18,
), ),
content("赌博诈骗", 7), content("不良封面/标题", 6),
SizedBox( SizedBox(
height: 18, height: 18,
), ),
content("违禁内容(暴利恐怖、令人不适、宣言仇恨)", 8), content("赌博诈骗", 7),
SizedBox( SizedBox(
height: 18, height: 18,
), ),
content("其他", 9), content("违禁内容(暴利恐怖、令人不适、宣言仇恨)", 8),
], SizedBox(
)); height: 18,
),
content("其他", 9),
],
),
);
} }
var checkIndex = 0; var checkIndex = 0;
@ -263,33 +290,34 @@ class _ReportPage extends State<ReportPage> {
Widget content(textContext, var index) { Widget content(textContext, var index) {
return GestureDetector( return GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () { onTap: () {
setState(() { setState(() {
checkIndex = index; checkIndex = index;
textCon = textContext; textCon = textContext;
}); });
}, },
child: Container( child: Container(
alignment: Alignment.center, alignment: Alignment.center,
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
checkView(index), checkView(index),
Container(), Container(),
Expanded( Expanded(
child: Text( child: Text(
textContext, textContext,
style: TextStyle( style: TextStyle(
fontSize: 16.sp, fontSize: 16.sp,
color: Color(0xFF353535), color: Color(0xFF353535),
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
),
), ),
) ),
], ),
), ],
)); ),
),
);
} }
} }

2
lib/community/report/report_success.dart

@ -15,7 +15,7 @@ class ReportSuccess extends StatefulWidget {
} }
class _ReportSuccess extends State<ReportSuccess> { class _ReportSuccess extends State<ReportSuccess> {
ApiService? apiService;
int checkIndex = 0; int checkIndex = 0;
@override @override

207
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/data/base_data.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:huixiang/utils/shared_preference.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../../generated/l10n.dart'; import '../../generated/l10n.dart';
import '../../utils/font_weight.dart'; import '../../utils/font_weight.dart';
@ -27,7 +28,7 @@ class ShareTrends extends StatefulWidget {
} }
} }
class _ShareTrends extends State<ShareTrends>{ class _ShareTrends extends State<ShareTrends> {
ApiService? apiService; ApiService? apiService;
bool topSetting = false; bool topSetting = false;
final TextEditingController textController = TextEditingController(); final TextEditingController textController = TextEditingController();
@ -42,17 +43,14 @@ class _ShareTrends extends State<ShareTrends>{
/// ///
queryDetails(id) async { queryDetails(id) async {
SharedPreferences value = await SharedPreferences.getInstance(); apiService ??= ApiService(Dio(),
if (apiService == null)
apiService = ApiService(
Dio(),
context: context, context: context,
token: value.getString("token"), token: SharedInstance.instance.token,
showLoading: true showLoading: true,
); );
BaseData<Article>? baseData = BaseData<Article>? baseData = await apiService?.informationInfo(id).catchError((onError) {
await apiService?.informationInfo(id).catchError((onError) {
debugPrint(onError.toString()); debugPrint(onError.toString());
return BaseData<Article>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
@ -65,34 +63,13 @@ class _ShareTrends extends State<ShareTrends>{
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
backgroundColor: Color(0xFFF9FAF7), 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( body: Container(
child: Column( child: Column(
children: [ children: [
Container( 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, color: Colors.white,
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
@ -101,19 +78,26 @@ class _ShareTrends extends State<ShareTrends>{
Expanded( Expanded(
child: Container( child: Container(
alignment: Alignment.center, alignment: Alignment.center,
margin: EdgeInsets.only(left:60.w,), margin: EdgeInsets.only(
child: Text( left: 60.w,
"转发", ),
style: TextStyle( child: Text(
color: Colors.black, "转发",
fontSize:17.sp, style: TextStyle(
fontWeight: MyFontWeight.regular, color: Colors.black,
fontSize: 17.sp,
fontWeight: MyFontWeight.regular,
),
), ),
),)), ),
),
Container( Container(
alignment: Alignment.center , alignment: Alignment.center,
margin:EdgeInsets.only(right: 16.w) , margin: EdgeInsets.only(right: 16.w),
padding: EdgeInsets.symmetric(horizontal: 16.w,vertical: 3.h), padding: EdgeInsets.symmetric(
horizontal: 16.w,
vertical: 3.h,
),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Color(0xFF32A060), color: Color(0xFF32A060),
borderRadius: BorderRadius.circular(10.5), borderRadius: BorderRadius.circular(10.5),
@ -122,7 +106,7 @@ class _ShareTrends extends State<ShareTrends>{
S.of(context).fabu, S.of(context).fabu,
style: TextStyle( style: TextStyle(
color: Colors.white, color: Colors.white,
fontSize:12.sp, fontSize: 12.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
), ),
), ),
@ -130,12 +114,12 @@ class _ShareTrends extends State<ShareTrends>{
], ],
), ),
), ),
Expanded(child: Expanded(
Container( child: Container(
margin: EdgeInsets.symmetric(vertical: 14.h), margin: EdgeInsets.symmetric(vertical: 14.h),
width: double.infinity, width: double.infinity,
color: Colors.white, color: Colors.white,
padding: EdgeInsets.only(left: 20.w,right: 16.w), padding: EdgeInsets.only(left: 20.w, right: 16.w),
child: Column( child: Column(
children: [ children: [
Container( Container(
@ -145,15 +129,17 @@ class _ShareTrends extends State<ShareTrends>{
), ),
margin: EdgeInsets.only(top: 30.w), margin: EdgeInsets.only(top: 30.w),
child: Container( child: Container(
margin: EdgeInsets.only(left:16.w,right: 10.w,), margin: EdgeInsets.only(
left: 16.w,
right: 10.w,
),
alignment: Alignment.topLeft, alignment: Alignment.topLeft,
child: TextField( child: TextField(
textInputAction:TextInputAction.send, textInputAction: TextInputAction.send,
onEditingComplete: () { onEditingComplete: () {},
},
maxLines: 8, maxLines: 8,
minLines: 1, minLines: 1,
focusNode:commentFocus, focusNode: commentFocus,
controller: textController, controller: textController,
decoration: InputDecoration( decoration: InputDecoration(
border: InputBorder.none, border: InputBorder.none,
@ -167,60 +153,75 @@ class _ShareTrends extends State<ShareTrends>{
), ),
), ),
GestureDetector( GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: (){ onTap: () {
Navigator.of(context).pushNamed( Navigator.of(context).pushNamed(
'/router/scan_web', '/router/scan_web',
arguments: { arguments: {
"result": widget.arguments?["shareUrl"], "result": widget.arguments?["shareUrl"],
"title":"一心回乡", "title": "一心回乡",
}, },
); );
}, },
child: Container( child: Container(
decoration: BoxDecoration( decoration: BoxDecoration(
color: Color(0xFFF2F2F2), color: Color(0xFFF2F2F2),
borderRadius: BorderRadius.circular(6), borderRadius: BorderRadius.circular(6),
), ),
padding: EdgeInsets.only(top: 8.h,bottom: 8.h,left: 8.w,right: 10.w), padding: EdgeInsets.only(
margin: EdgeInsets.only(top: 12.w), top: 8.h,
child: Row( bottom: 8.h,
mainAxisAlignment: MainAxisAlignment.center, left: 8.w,
crossAxisAlignment: CrossAxisAlignment.start, right: 10.w,
children: [ ),
if(article?.content != null && article!.content!.contains("images\":[\"") || (article?.coverImg ?? "")!= "") margin: EdgeInsets.only(top: 12.w),
MImage( child: Row(
article?.content != null && mainAxisAlignment: MainAxisAlignment.center,
article!.content!.contains("images\":[\"") crossAxisAlignment: CrossAxisAlignment.start,
? jsonDecode(article!.content!)["images"][0] children: [
: article?.coverImg ?? "", if (article?.content != null &&
radius: BorderRadius.circular(2), article!.content!
fit: BoxFit.fill, .contains("images\":[\"") ||
width: 64, (article?.coverImg ?? "") != "")
height: 64, MImage(
errorSrc: "assets/image/default_2_1.webp", article?.content != null &&
fadeSrc: "assets/image/default_2_1.webp", article!.content!
), .contains("images\":[\"")
if(article?.content != null || article?.coverImg != null) ? jsonDecode(article!.content!)["images"][0]
SizedBox(width: 7.w,), : article?.coverImg ?? "",
Expanded(child: Text( radius: BorderRadius.circular(2),
article?.mainTitle ?? "", fit: BoxFit.fill,
maxLines: 3, width: 64,
overflow: TextOverflow.ellipsis, height: 64,
style: TextStyle( errorSrc: "assets/image/default_2_1.webp",
color: Color(0xFF4D4D4D), fadeSrc: "assets/image/default_2_1.webp",
fontSize:14.sp, ),
height: 1.4.h, if (article?.content != null ||
fontWeight: MyFontWeight.regular, 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,
),
),
), ),
),), ],
], ),
), ),
)), ),
], ],
), ),
), ),
) ),
], ],
), ),
), ),

16
lib/constant.dart

@ -7,24 +7,26 @@ const String chatImageHost = "http://skk8mlm5b.hn-bkt.clouddn.com/";
/// socket的host和port端口 /// socket的host和port端口
//47.93.216.24:9090 线 192.168.10.200/192.168.10.129:9090 //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 int socketPort = 9090;
const ipBaseUrl = "http://whois.pconline.com.cn"; 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接口的请求地址 /// app接口的请求地址
const localMiniBaseUrl = "https://pos.api.yixinhuixiang.com/app/";
const serviceMiniBaseUrl = "https://pos.api.yixinhuixiang.com/app/"; const serviceMiniBaseUrl = "https://pos.api.yixinhuixiang.com/app/";
///线 ///线
/// 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/"; const serviceBaseUrl = "https://pos.platform.yixinhuixiang.com/app/";
///线 /// 线
/// list进行分组 /// list进行分组
Map<S, List<T>> groupBy<S, T>(Iterable<T> values, S Function(T) key) { Map<S, List<T>> groupBy<S, T>(Iterable<T> values, S Function(T) key) {
var map = <S, List<T>>{}; var map = <S, List<T>>{};
@ -61,16 +63,16 @@ Map<String, T> groupItem<S, T>(Map<S, List<T>> values, {int Function(T)? key}) {
/// ///
T max<T>(Iterable<T> list, int Function(T) key) { T max<T>(Iterable<T> list, int Function(T) key) {
late T tt; T? tt;
for (T t in list) { for (T t in list) {
if (tt == null) { if (tt == null) {
tt = t; tt = t;
} }
if (key(tt) < key(t)) { if (key(tt!) < key(t)) {
tt = t; tt = t;
} }
} }
return tt; return tt!;
} }
extension ListExtension<S, T> on Iterable<T> { extension ListExtension<S, T> on Iterable<T> {

2
lib/data/article.dart

@ -16,7 +16,7 @@ class Article {
dynamic viceTitle; dynamic viceTitle;
String? content = ''; String? content = '';
String? coverImg = ''; String? coverImg = '';
Author? author; dynamic author;
int? type = 0; int? type = 0;
int? likes = 0; int? likes = 0;
int? viewers = 0; int? viewers = 0;

6
lib/data/article.g.dart

@ -18,9 +18,7 @@ Article _$ArticleFromJson(Map<String, dynamic> json) => Article()
..viceTitle = json['viceTitle'] ..viceTitle = json['viceTitle']
..content = json['content'] as String? ..content = json['content'] as String?
..coverImg = json['coverImg'] as String? ..coverImg = json['coverImg'] as String?
..author = json['author'] == null ..author = json['author']
? null
: Author.fromJson(json['author'] as Map<String, dynamic>)
..type = (json['type'] as num?)?.toInt() ..type = (json['type'] as num?)?.toInt()
..likes = (json['likes'] as num?)?.toInt() ..likes = (json['likes'] as num?)?.toInt()
..viewers = (json['viewers'] as num?)?.toInt() ..viewers = (json['viewers'] as num?)?.toInt()
@ -53,7 +51,7 @@ Map<String, dynamic> _$ArticleToJson(Article instance) => <String, dynamic>{
'viceTitle': instance.viceTitle, 'viceTitle': instance.viceTitle,
'content': instance.content, 'content': instance.content,
'coverImg': instance.coverImg, 'coverImg': instance.coverImg,
'author': instance.author?.toJson(), 'author': instance.author,
'type': instance.type, 'type': instance.type,
'likes': instance.likes, 'likes': instance.likes,
'viewers': instance.viewers, 'viewers': instance.viewers,

32
lib/data/vip_card.dart

@ -1,3 +1,5 @@
import 'dart:ui';
import 'package:huixiang/data/store.dart'; import 'package:huixiang/data/store.dart';
import 'package:json_annotation/json_annotation.dart'; import 'package:json_annotation/json_annotation.dart';
@ -5,39 +7,69 @@ part 'vip_card.g.dart';
@JsonSerializable(explicitToJson: true) @JsonSerializable(explicitToJson: true)
class VipCard { class VipCard {
@JsonKey()
String? id = ''; String? id = '';
@JsonKey()
String? createTime = ''; String? createTime = '';
@JsonKey()
dynamic createUser; dynamic createUser;
@JsonKey()
String? updateTime = ''; String? updateTime = '';
@JsonKey()
String? updateUser = ''; String? updateUser = '';
@JsonKey()
String? mid = ''; String? mid = '';
@JsonKey()
String? openid = ''; String? openid = '';
@JsonKey()
String? nickname = ''; String? nickname = '';
@JsonKey()
String? headimg = ''; String? headimg = '';
@JsonKey()
String? balance = ''; String? balance = '';
@JsonKey()
String? realRecharge = ''; String? realRecharge = '';
@JsonKey()
String? sex = ''; String? sex = '';
@JsonKey()
bool? status = false; bool? status = false;
@JsonKey()
bool? onCredit = false; bool? onCredit = false;
@JsonKey()
String? loginTime = ''; String? loginTime = '';
@JsonKey()
int? loginNum = 0; int? loginNum = 0;
@JsonKey()
String? tenantCode = ''; String? tenantCode = '';
@JsonKey()
int? source = 0; int? source = 0;
@JsonKey()
String? expendAmount = ''; String? expendAmount = '';
@JsonKey()
int? buyTimes = 0; int? buyTimes = 0;
@JsonKey()
dynamic lastBuyTime; dynamic lastBuyTime;
@JsonKey(name: "vip_no") @JsonKey(name: "vip_no")
dynamic vipNo; dynamic vipNo;
@JsonKey()
dynamic expireTime; dynamic expireTime;
@JsonKey()
int? integral = 0; int? integral = 0;
@JsonKey()
int? level = 0; int? level = 0;
@JsonKey()
dynamic vipRegStore; dynamic vipRegStore;
@JsonKey()
String? tenantName = ''; String? tenantName = '';
@JsonKey()
String? tenantLogo = ''; String? tenantLogo = '';
@JsonKey()
List<Store>? storeList = []; List<Store>? storeList = [];
VipCard(); VipCard();
Color color = Color(0xFF32A060);
factory VipCard.fromJson(Map<String, dynamic> json) => _$VipCardFromJson(json); factory VipCard.fromJson(Map<String, dynamic> json) => _$VipCardFromJson(json);
Map<String, dynamic> toJson() => _$VipCardToJson(this); Map<String, dynamic> toJson() => _$VipCardToJson(this);

9
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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:keframe/keframe.dart'; import 'package:keframe/keframe.dart';
@ -39,9 +40,7 @@ class _ActivityListPage extends State<ActivityListPage>
List<Activity>? activityList; List<Activity>? activityList;
queryActivity() async { queryActivity() async {
final SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService =
ApiService(Dio(), context: context, token: value.getString('token'));
BaseData<PageInfo<Activity>>? baseData = await apiService?.informationList({ BaseData<PageInfo<Activity>>? baseData = await apiService?.informationList({
"pageNum": 1, "pageNum": 1,
"pageSize": 10, "pageSize": 10,
@ -50,7 +49,7 @@ class _ActivityListPage extends State<ActivityListPage>
"state": 1 "state": 1
}).catchError((error) { }).catchError((error) {
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return Future.value(null); return BaseData<PageInfo<Activity>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
_refreshController.refreshCompleted(); _refreshController.refreshCompleted();
@ -92,7 +91,7 @@ class _ActivityListPage extends State<ActivityListPage>
Navigator.of(context).pushNamed( Navigator.of(context).pushNamed(
'/router/web_page', '/router/web_page',
arguments: { arguments: {
"activityId": activityList![position].id "activityId": activityList![position].id,
}, },
); );
}, },

316
lib/home/founder_story_page.dart

@ -33,7 +33,9 @@ class _FounderStoryPage extends State<FounderStoryPage> {
children: [ children: [
Container( Container(
// margin: EdgeInsets.only(bottom: 20), // 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( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
boxShadow: [ boxShadow: [
@ -41,7 +43,8 @@ class _FounderStoryPage extends State<FounderStoryPage> {
color: Colors.black.withAlpha(12), color: Colors.black.withAlpha(12),
offset: Offset(0, 2), offset: Offset(0, 2),
blurRadius: 14, blurRadius: 14,
spreadRadius: 0,) spreadRadius: 0,
),
], ],
), ),
child: Column( child: Column(
@ -55,9 +58,13 @@ class _FounderStoryPage extends State<FounderStoryPage> {
SizedBox( SizedBox(
height: 16, height: 16,
), ),
Text("关于创始人", Text(
style: TextStyle( "关于创始人",
fontSize: 24.sp, color: Color(0xff565656))), style: TextStyle(
fontSize: 24.sp,
color: Color(0xff565656),
),
),
SizedBox( SizedBox(
height: 18.h, height: 18.h,
), ),
@ -75,8 +82,10 @@ class _FounderStoryPage extends State<FounderStoryPage> {
color: Color(0xFF1A1A1A), color: Color(0xFF1A1A1A),
fontSize: 12.sp, fontSize: 12.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
height: 1.5), height: 1.5,
)), ),
),
),
Padding( Padding(
padding: EdgeInsets.only(top: 50.h), padding: EdgeInsets.only(top: 50.h),
child: Align( child: Align(
@ -103,8 +112,10 @@ class _FounderStoryPage extends State<FounderStoryPage> {
color: Color(0xFF1A1A1A), color: Color(0xFF1A1A1A),
fontSize: 12.sp, fontSize: 12.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
height: 1.5.h), height: 1.5.h,
)), ),
),
),
Image.asset( Image.asset(
"assets/image/icon_story_2.webp", "assets/image/icon_story_2.webp",
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
@ -132,7 +143,9 @@ class _FounderStoryPage extends State<FounderStoryPage> {
style: TextStyle( style: TextStyle(
fontSize: 24.sp, fontSize: 24.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Color(0xff565656))), color: Color(0xff565656),
),
),
SizedBox( SizedBox(
height: 20, height: 20,
), ),
@ -149,7 +162,9 @@ class _FounderStoryPage extends State<FounderStoryPage> {
style: TextStyle( style: TextStyle(
fontSize: 16.sp, fontSize: 16.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Color(0xff565656))), color: Color(0xff565656),
),
),
), ),
_textWidget("2019年,在武汉成立湖北海峡姐妹餐饮有限公司。" _textWidget("2019年,在武汉成立湖北海峡姐妹餐饮有限公司。"
"成为百年川椒火锅(光谷店)运营方,通过“素食煮义”和“蔬食之力”推广有机永续美好生活," "成为百年川椒火锅(光谷店)运营方,通过“素食煮义”和“蔬食之力”推广有机永续美好生活,"
@ -169,7 +184,9 @@ class _FounderStoryPage extends State<FounderStoryPage> {
style: TextStyle( style: TextStyle(
fontSize: 24.sp, fontSize: 24.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Color(0xff565656))), color: Color(0xff565656),
),
),
SizedBox( SizedBox(
height: 26.h, height: 26.h,
), ),
@ -205,7 +222,8 @@ class _FounderStoryPage extends State<FounderStoryPage> {
color: Colors.black.withAlpha(12), color: Colors.black.withAlpha(12),
offset: Offset(0, 2), offset: Offset(0, 2),
blurRadius: 14, blurRadius: 14,
spreadRadius: 0) spreadRadius: 0,
),
], ],
), ),
child: RichText( child: RichText(
@ -217,8 +235,10 @@ class _FounderStoryPage extends State<FounderStoryPage> {
color: Colors.white, color: Colors.white,
fontSize: 12.sp, fontSize: 12.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
height: 1.5.h), height: 1.5.h,
)), ),
),
),
), ),
Padding( Padding(
padding: EdgeInsets.only( padding: EdgeInsets.only(
@ -233,11 +253,14 @@ class _FounderStoryPage extends State<FounderStoryPage> {
SizedBox( SizedBox(
height: 27.h, height: 27.h,
), ),
Text("传递理念", Text(
"传递理念",
style: TextStyle( style: TextStyle(
fontSize: 24.sp, fontSize: 24.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Color(0xff565656))), color: Color(0xff565656),
),
),
SizedBox( SizedBox(
height: 20.h, height: 20.h,
), ),
@ -264,108 +287,6 @@ class _FounderStoryPage extends State<FounderStoryPage> {
], ],
), ),
), ),
// 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<FounderStoryPage> {
children: [ children: [
Text( Text(
"", "",
style: TextStyle(fontSize: 10.sp, color: Color(0xff32A060)), style: TextStyle(
fontSize: 10.sp,
color: Color(0xff32A060),
),
), ),
SizedBox( SizedBox(
width: 5.w, width: 5.w,
@ -392,7 +316,10 @@ class _FounderStoryPage extends State<FounderStoryPage> {
style: TextStyle( style: TextStyle(
fontSize: 12.sp, fontSize: 12.sp,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
color: Colors.black))), color: Colors.black,
),
),
),
], ],
), ),
); );
@ -421,23 +348,11 @@ class _FounderStoryPage extends State<FounderStoryPage> {
style: TextStyle( style: TextStyle(
fontSize: 18.sp, fontSize: 18.sp,
fontWeight: MyFontWeight.light, 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( Container(
width: 73.w, width: 73.w,
@ -446,136 +361,13 @@ class _FounderStoryPage extends State<FounderStoryPage> {
painter: MyPainter( painter: MyPainter(
lineColor: Color(0xff32A060), lineColor: Color(0xff32A060),
width: 2.w, 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)),
// ),
// ),
// ],
// ),
// );
// }
} }

55
lib/home/guide_page.dart

@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/utils/constant.dart'; import 'package:huixiang/utils/constant.dart';
import 'package:huixiang/utils/font_weight.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/border_text.dart';
import 'package:huixiang/view_widget/round_button.dart'; import 'package:huixiang/view_widget/round_button.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -27,24 +28,9 @@ class _GuidePage extends State<GuidePage> {
} }
isLogin() async { isLogin() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (!SharedInstance.instance.isShowPrivacyPolicy) {
if (sharedPreferences.getBool("isShowPrivacyPolicy") == null ||
!(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) {
showAlertDialog(); 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 @override
@ -70,7 +56,9 @@ class _GuidePage extends State<GuidePage> {
color: Colors.white, color: Colors.white,
child: Center( child: Center(
child: Container( 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( child: Stack(
children: [ children: [
Column( Column(
@ -164,7 +152,9 @@ class _GuidePage extends State<GuidePage> {
color: Colors.white, color: Colors.white,
child: Center( child: Center(
child: Container( 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( child: Stack(
children: [ children: [
Column( Column(
@ -478,7 +468,8 @@ class _GuidePage extends State<GuidePage> {
child: Column( child: Column(
children: [ children: [
Text.rich( Text.rich(
TextSpan(children: [ TextSpan(
children: [
TextSpan( TextSpan(
text: S.of(context).yinsizhengce1, text: S.of(context).yinsizhengce1,
style: TextStyle( style: TextStyle(
@ -497,11 +488,11 @@ class _GuidePage extends State<GuidePage> {
), ),
recognizer: TapGestureRecognizer() recognizer: TapGestureRecognizer()
..onTap = () { ..onTap = () {
Navigator.of(context) Navigator.of(context).popAndPushNamed('/router/treaty_page');
.popAndPushNamed('/router/treaty_page');
}, },
), ),
]), ],
),
), ),
10.d, 10.d,
Text( Text(
@ -557,9 +548,7 @@ class _GuidePage extends State<GuidePage> {
textColor: Colors.white, textColor: Colors.white,
fontSize: 12.sp, fontSize: 12.sp,
callback: () { callback: () {
SharedPreferences.getInstance().then((value) { SharedInstance.instance.showPrivacyPolicy();
value.setBool("isShowPrivacyPolicy", true);
});
SharesdkPlugin.uploadPrivacyPermissionStatus( SharesdkPlugin.uploadPrivacyPermissionStatus(
1, 1,
(success) { (success) {
@ -591,14 +580,12 @@ class _GuidePage extends State<GuidePage> {
} }
toNext() { toNext() {
SharedPreferences.getInstance().then((value) { SharedInstance.instance.setFirst();
value.setBool("isFirst", false); String token = SharedInstance.instance.token;
String? token = value.getString("token"); if (token.isEmpty) {
if (token?.isEmpty ?? true) { Navigator.of(context).popAndPushNamed('/router/new_login_page');
Navigator.of(context).popAndPushNamed('/router/new_login_page'); } else {
} else { Navigator.of(context).popAndPushNamed('/router/main_page');
Navigator.of(context).popAndPushNamed('/router/main_page'); }
}
});
} }
} }

63
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/generated/l10n.dart';
import 'package:huixiang/home/help_farmers/farmers_tab.dart'; import 'package:huixiang/home/help_farmers/farmers_tab.dart';
import 'package:huixiang/retrofit/retrofit_api.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:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:shimmer/shimmer.dart'; import 'package:shimmer/shimmer.dart';
@ -38,20 +39,18 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(Dio(),
apiService = ApiService(Dio(), context: context,
context: context, token: SharedInstance.instance.token,
token: value.getString('token'), showLoading: true,
showLoading: true), );
queryConfig(), queryConfig();
});
} }
/// ///
queryConfig() async { queryConfig() async {
try { try {
BaseListData<Farmers>? baseData = BaseListData<Farmers>? baseData = await apiService?.getConfig().catchError((error) {
await apiService?.getConfig().catchError((error) {
networkStatus = -1; networkStatus = -1;
refreshController.refreshFailed(); refreshController.refreshFailed();
return BaseListData<Farmers>()..isSuccess = false; return BaseListData<Farmers>()..isSuccess = false;
@ -224,7 +223,9 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
isShowBtn: false, isShowBtn: false,
text: "当前分类暂无商品", text: "当前分类暂无商品",
fontSize: 16.sp, 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( : StaggeredGrid.count(
crossAxisCount: 2, crossAxisCount: 2,
@ -260,7 +261,7 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
offset: Offset(0, 2), offset: Offset(0, 2),
blurRadius: 4, blurRadius: 4,
spreadRadius: 0, spreadRadius: 0,
) ),
], ],
color: Colors.white, color: Colors.white,
), ),
@ -298,12 +299,13 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
), ),
), ),
Padding( Padding(
padding: EdgeInsets.only(left: 10.w, bottom: 12.h), padding: EdgeInsets.only(
left: 10.w, bottom: 12.h,
),
child: Row( child: Row(
children: [ children: [
Text( Text(
AppUtils.calculateDouble( AppUtils.calculateDouble(double.tryParse("${goodList.price}") ?? 0),
double.tryParse("${goodList.price}") ?? 0),
style: TextStyle( style: TextStyle(
fontSize: 24.sp, fontSize: 24.sp,
fontFamily: 'APPHT', fontFamily: 'APPHT',
@ -313,7 +315,9 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
), ),
Container( Container(
margin: EdgeInsets.only(left: 8.w), 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( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100), borderRadius: BorderRadius.circular(100),
boxShadow: [ boxShadow: [
@ -355,8 +359,9 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
offset: Offset(0, 1), offset: Offset(0, 1),
blurRadius: 12, blurRadius: 12,
spreadRadius: 0, spreadRadius: 0,
) ),
]), ],
),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@ -372,7 +377,9 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
Row( Row(
children: [ children: [
Padding( 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( child: Shimmer.fromColors(
baseColor: Color(0XFFD8D8D8), baseColor: Color(0XFFD8D8D8),
highlightColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8),
@ -387,7 +394,9 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
), ),
), ),
Padding( 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( child: Shimmer.fromColors(
baseColor: Color(0XFFD8D8D8), baseColor: Color(0XFFD8D8D8),
highlightColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8),
@ -402,7 +411,9 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
), ),
), ),
Padding( 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( child: Shimmer.fromColors(
baseColor: Color(0XFFD8D8D8), baseColor: Color(0XFFD8D8D8),
highlightColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8),
@ -417,7 +428,9 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
), ),
), ),
Padding( 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( child: Shimmer.fromColors(
baseColor: Color(0XFFD8D8D8), baseColor: Color(0XFFD8D8D8),
highlightColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8),
@ -457,8 +470,9 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
), ),
), ),
Padding( Padding(
padding: padding: EdgeInsets.only(
EdgeInsets.only(top: 7.h, left: 10.w, bottom: 8.h), top: 7.h, left: 10.w, bottom: 8.h,
),
child: Shimmer.fromColors( child: Shimmer.fromColors(
baseColor: Color(0XFFD8D8D8), baseColor: Color(0XFFD8D8D8),
highlightColor: Color(0XFFD8D8D8), highlightColor: Color(0XFFD8D8D8),
@ -509,7 +523,8 @@ class _HelpFarmersPage extends State<HelpFarmersPage> {
), ),
); );
}, },
)), ),
),
], ],
), ),
); );

108
lib/home/home_page.dart

@ -6,8 +6,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.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/activity_pos.dart';
import 'package:huixiang/data/article.dart'; import 'package:huixiang/data/article.dart';
import 'package:huixiang/data/banner.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/home_rank.dart';
import 'package:huixiang/data/login_info.dart'; import 'package:huixiang/data/login_info.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/data/user_info.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/home/home_view/discount_zone.dart'; import 'package:huixiang/home/home_view/discount_zone.dart';
import 'package:huixiang/home/home_view/home_recommend_goods.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/main.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.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_coupons.dart';
import 'package:huixiang/view_widget/activity_poster.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/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/invite_success_dialog.dart';
import 'package:huixiang/view_widget/request_permission.dart'; import 'package:huixiang/view_widget/request_permission.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.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/happy_help_farmers.dart';
import 'home_view/shortcut_operation.dart'; import 'home_view/shortcut_operation.dart';
@ -99,29 +97,20 @@ class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
setState(() {}); setState(() {});
} }
}); });
if (apiService == null) { apiService = ApiService(
SharedPreferences.getInstance().then((value) { Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString("token"), _onRefresh(isFirstIn: true);
);
_onRefresh(isFirstIn: true);
});
}
if (showInvite) { if (showInvite) {
inviteShowAlertDialog(widget.invite, widget.interviewCouponList?[0]); inviteShowAlertDialog(widget.invite, widget.interviewCouponList?[0]);
showInvite = false; showInvite = false;
} }
if ((widget.invite?.isNotEmpty ?? false) || if ((widget.invite?.isNotEmpty ?? false) || (widget.interviewCouponList?.isNotEmpty ?? false)) {
(widget.interviewCouponList?.isNotEmpty ?? false)) {
showInvite = true; showInvite = true;
} }
//
// if (widget.firstLoginCouponList != null && widget.firstLoginCouponList.length > 0)
// showNew = true;
} }
/// ///
@ -138,22 +127,18 @@ class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
/// ///
posterShowAlertDialog(ActivityPos? activityPos, firstLoginCouponList) { posterShowAlertDialog(ActivityPos? activityPos, firstLoginCouponList) {
var today = DateTime.now().day; var today = DateTime.now().day;
SharedPreferences.getInstance().then((value) {
if (value.getInt("today") == today && if (SharedInstance.instance.today == today && (SharedInstance.instance.ActivityPosCode).contains("${activityPos?.code}_${SharedInstance.instance.userId};"))
(value.getString("ActivityPosCode") ?? "") return;
.contains("${activityPos?.code}_${value.getString("userId")};")) SharedInstance.instance.saveActivityPosCode("${SharedInstance.instance.ActivityPosCode}${activityPos?.code}_${SharedInstance.instance.userId};");
return; SharedInstance.instance.saveToday(today);
value.setString("ActivityPosCode", //
"${(value.getString("ActivityPosCode") ?? "")}${activityPos?.code}_${value.getString("userId")};"); showDialog(
value.setInt("today", today); context: context,
// builder: (BuildContext context) {
showDialog( return ActivityPoster(activityPos, firstLoginCouponList);
context: context, },
builder: (BuildContext context) { );
return ActivityPoster(activityPos, firstLoginCouponList);
},
);
});
} }
/// ///
@ -309,7 +294,7 @@ class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
// apiService = ApiService( // apiService = ApiService(
// Dio(), // Dio(),
// context: context, // context: context,
// token: value.getString("token"), // token: SharedInstance.instance.token,
// ); // );
// } // }
// BaseData<List<MsgStats>>? baseData = await apiService?.stats().catchError((onError) {}); // BaseData<List<MsgStats>>? baseData = await apiService?.stats().catchError((onError) {});
@ -337,22 +322,16 @@ class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
/// ///
queryWiped(memberCouponId) async { queryWiped(memberCouponId) async {
if (apiService == null) { apiService ??= ApiService(
SharedPreferences.getInstance().then((value) { Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString("token"),
);
});
}
BaseData? baseData = await apiService?.wiped(memberCouponId).catchError((onError) { BaseData? baseData = await apiService?.wiped(memberCouponId).catchError((onError) {
return BaseData()..isSuccess = false; return BaseData()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
SmartDialog.showToast("核销成功", alignment: Alignment.center); SmartDialog.showToast("核销成功", alignment: Alignment.center);
} else {
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center);
} }
} }
@ -556,18 +535,26 @@ class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
bannerClick(BannerData bannerData) async { bannerClick(BannerData bannerData) async {
switch (bannerData.contentType) { switch (bannerData.contentType) {
case 1: case 1:
Navigator.of(context).pushNamed('/router/integral_store_page', Navigator.of(context).pushNamed(
arguments: {"goodsId": bannerData.content}); '/router/integral_store_page',
arguments: {
"goodsId": bannerData.content,
},
);
break; break;
case 2: case 2:
Navigator.of(context).pushNamed('/router/web_page', arguments: { Navigator.of(context).pushNamed(
"activityId": bannerData.content, '/router/web_page', arguments: {
}); "activityId": bannerData.content,
},
);
break; break;
case 3: case 3:
Navigator.of(context).pushNamed('/router/web_page', arguments: { Navigator.of(context).pushNamed(
"articleId": bannerData.content, '/router/web_page', arguments: {
}); "articleId": bannerData.content,
},
);
break; break;
case 4: case 4:
String? router = bannerData.content; String? router = bannerData.content;
@ -599,7 +586,8 @@ class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
Map map = jsonDecode(params); Map map = jsonDecode(params);
Navigator.of(context).pushNamed( Navigator.of(context).pushNamed(
router.substring(0, router.indexOf("?")), router.substring(0, router.indexOf("?")),
arguments: map); arguments: map,
);
break; break;
} }
} }

6
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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
@ -41,8 +42,7 @@ class _ActivityList extends State<ActivityList>
List<Activity>? activityList; List<Activity>? activityList;
queryActivity() async { queryActivity() async {
final SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = ApiService(Dio(), context: context, token: value.getString('token'));
BaseData<PageInfo<Activity>>? baseData = await apiService?.informationList({ BaseData<PageInfo<Activity>>? baseData = await apiService?.informationList({
"pageNum": 1, "pageNum": 1,
"pageSize": 10, "pageSize": 10,
@ -51,7 +51,7 @@ class _ActivityList extends State<ActivityList>
"state": 1 "state": 1
}).catchError((error) { }).catchError((error) {
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return Future.value(null); return BaseData<PageInfo<Activity>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
_refreshController.refreshCompleted(); _refreshController.refreshCompleted();

2
lib/home/home_view/brand_view.dart

@ -72,7 +72,7 @@ class _BrandView extends State<BrandView> {
), ),
); );
}, },
itemCount: widget.brandData.length ?? 0, itemCount: widget.brandData.length,
), ),
); );
} }

27
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/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/item_title.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/view_widget/receive_success.dart'; import 'package:huixiang/view_widget/receive_success.dart';
@ -29,15 +30,12 @@ class _CouponView extends State<CouponView> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
apiService = ApiService(
SharedPreferences.getInstance().then((value) => { Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString('token'), queryCoupon();
),
queryCoupon(),
});
} }
queryCoupon() async { queryCoupon() async {
@ -48,7 +46,7 @@ class _CouponView extends State<CouponView> {
"searchKey": "", "searchKey": "",
"state": 0 "state": 0
}).catchError((onError) { }).catchError((onError) {
return Future.value(null); return BaseData<PageInfo<Coupon>>()..isSuccess = false;
}); });
coupons.clear(); coupons.clear();
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -78,7 +76,7 @@ class _CouponView extends State<CouponView> {
itemBuilder: (context, position) { itemBuilder: (context, position) {
return couponItem(coupons[position]); return couponItem(coupons[position]);
}, },
itemCount:coupons == null ? 0 : coupons.length, itemCount: coupons.length,
), ),
), ),
], ],
@ -177,8 +175,8 @@ class _CouponView extends State<CouponView> {
Expanded( Expanded(
child: Container( child: Container(
margin: EdgeInsets.symmetric( margin: EdgeInsets.symmetric(
vertical: 10.h, horizontal: 15.w, vertical: 10.h, horizontal: 15.w,
), ),
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@ -271,7 +269,8 @@ class _CouponView extends State<CouponView> {
receiveCoupon(couponId) async { receiveCoupon(couponId) async {
BaseData? baseData = await apiService?.receiveCoupon(couponId).catchError((onError) { BaseData? baseData = await apiService?.receiveCoupon(couponId).catchError((onError) {
return Future.value(null);}); return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
queryCoupon(); queryCoupon();
showAlertDialog(); showAlertDialog();

1
lib/home/home_view/discount_zone.dart

@ -18,7 +18,6 @@ class DiscountZone extends StatefulWidget {
} }
class _DiscountZone extends State<DiscountZone> { class _DiscountZone extends State<DiscountZone> {
ApiService? apiService;
@override @override
void initState() { void initState() {

49
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/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/item_title.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -29,8 +30,7 @@ class _FeaturedActivity extends State<FeaturedActivity> {
List<Activity>? activityList; List<Activity>? activityList;
queryActivity() async { queryActivity() async {
final SharedPreferences value = await SharedPreferences.getInstance(); apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = ApiService(Dio(), context: context, token: value.getString('token'));
BaseData<PageInfo<Activity>>? baseData = await apiService?.informationList({ BaseData<PageInfo<Activity>>? baseData = await apiService?.informationList({
"pageNum": 1, "pageNum": 1,
"pageSize": 10, "pageSize": 10,
@ -38,7 +38,8 @@ class _FeaturedActivity extends State<FeaturedActivity> {
"type": 1, "type": 1,
"state": 1 "state": 1
}).catchError((error) { }).catchError((error) {
return Future.value(null);}); return BaseData<PageInfo<Activity>>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
activityList = baseData?.data?.list ?? []; activityList = baseData?.data?.list ?? [];
if (activityList!.length == 1) if (activityList!.length == 1)
@ -70,8 +71,10 @@ class _FeaturedActivity extends State<FeaturedActivity> {
if (activityList?.isNotEmpty ?? false) if (activityList?.isNotEmpty ?? false)
GestureDetector( GestureDetector(
onTap: () { onTap: () {
Navigator.of(context).pushNamed('/router/web_page', Navigator.of(context).pushNamed(
arguments: {"activityId": activityList?[0].id}); '/router/web_page',
arguments: {"activityId": activityList?[0].id},
);
}, },
child: Container( child: Container(
child: stackItem(18.sp, activityList?[0]), child: stackItem(18.sp, activityList?[0]),
@ -98,8 +101,10 @@ class _FeaturedActivity extends State<FeaturedActivity> {
children: [ children: [
GestureDetector( GestureDetector(
onTap: () { onTap: () {
Navigator.of(context).pushNamed('/router/web_page', Navigator.of(context).pushNamed(
arguments: {"activityId": activityList?[1].id}); '/router/web_page',
arguments: {"activityId": activityList?[1].id},
);
}, },
child: Container( child: Container(
child: stackItem(12.sp, activityList?[1]), child: stackItem(12.sp, activityList?[1]),
@ -118,31 +123,6 @@ class _FeaturedActivity extends State<FeaturedActivity> {
), ),
), ),
), ),
// 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<FeaturedActivity> {
), ),
Spacer() Spacer()
], ],
) ),
], ],
)); ),
);
} }
} }

7
lib/home/home_view/founder_store.dart

@ -32,8 +32,7 @@ class _FounderStore extends State<FounderStore> {
), ),
GestureDetector( GestureDetector(
onTap: () { onTap: () {
Navigator.of(context) Navigator.of(context).pushNamed('/router/founder_story_page');
.pushNamed('/router/founder_story_page');
}, },
child: founderStore(), child: founderStore(),
), ),
@ -44,7 +43,9 @@ class _FounderStore extends State<FounderStore> {
Widget founderStore() { Widget founderStore() {
return Container( 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( decoration: BoxDecoration(
boxShadow: [ boxShadow: [
BoxShadow( BoxShadow(

2
lib/home/home_view/happy_help_farmers.dart

@ -13,14 +13,12 @@ class HappyHelpFarmers extends StatefulWidget {
} }
class _HappyHelpFarmers extends State<HappyHelpFarmers> { class _HappyHelpFarmers extends State<HappyHelpFarmers> {
ApiService? apiService;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(

33
lib/home/home_view/home_banner.dart

@ -75,18 +75,26 @@ class _HomeBanner extends State<HomeBanner> {
bannerClick(BannerData bannerData) async { bannerClick(BannerData bannerData) async {
switch (bannerData.contentType) { switch (bannerData.contentType) {
case 1: case 1:
Navigator.of(context).pushNamed('/router/integral_store_page', Navigator.of(context).pushNamed(
arguments: {"goodsId": bannerData.content}); '/router/integral_store_page',
arguments: {"goodsId": bannerData.content},
);
break; break;
case 2: case 2:
Navigator.of(context).pushNamed('/router/web_page', arguments: { Navigator.of(context).pushNamed(
"activityId": bannerData.content, '/router/web_page',
}); arguments: {
"activityId": bannerData.content,
},
);
break; break;
case 3: case 3:
Navigator.of(context).pushNamed('/router/web_page', arguments: { Navigator.of(context).pushNamed(
"articleId": bannerData.content, '/router/web_page',
}); arguments: {
"articleId": bannerData.content,
},
);
break; break;
case 4: case 4:
String? router = bannerData.content; String? router = bannerData.content;
@ -105,9 +113,12 @@ class _HomeBanner extends State<HomeBanner> {
} }
break; break;
case 5: case 5:
Navigator.of(context).pushNamed('/router/class_details', arguments: { Navigator.of(context).pushNamed(
"id": bannerData.content, '/router/class_details',
}); arguments: {
"id": bannerData.content,
},
);
break; break;
case 7: case 7:
String? router = bannerData.content; String? router = bannerData.content;

10
lib/home/home_view/home_integral_store.dart

@ -45,7 +45,9 @@ class _HomeIntegralStore extends State<HomeIntegralStore> {
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ 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, S.of(context).dajiadouzaiduihuan,
textAlign: TextAlign.end, textAlign: TextAlign.end,
style: TextStyle( style: TextStyle(
@ -85,8 +87,10 @@ class _HomeIntegralStore extends State<HomeIntegralStore> {
itemBuilder: (context, index) { itemBuilder: (context, index) {
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
Navigator.of(context).pushNamed('/router/integral_store_page', Navigator.of(context).pushNamed(
arguments: {"goodsId": widget.gooods[index].id}); '/router/integral_store_page',
arguments: {"goodsId": widget.gooods[index].id},
);
}, },
child: buildItem(widget.gooods[index]), child: buildItem(widget.gooods[index]),
); );

8
lib/home/home_view/home_recommend_goods.dart

@ -1,8 +1,10 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:huixiang/data/home_rank.dart'; import 'package:huixiang/data/home_rank.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/app_util.dart';
import 'package:huixiang/utils/flutter_utils.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:huixiang/view_widget/custom_image.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/utils/font_weight.dart';
@ -25,6 +27,11 @@ class _HomeRecommendGoods extends State<HomeRecommendGoods> {
@override @override
void initState() { void initState() {
apiService = ApiService(
Dio(),
context: context,
token: SharedInstance.instance.token,
);
super.initState(); super.initState();
} }
@ -145,4 +152,5 @@ class _HomeRecommendGoods extends State<HomeRecommendGoods> {
), ),
); );
} }
} }

11
lib/home/home_view/hot_article.dart

@ -29,8 +29,7 @@ class _HotArticle extends State<HotArticle> {
imgPath: "assets/image/icon_today_video.webp", imgPath: "assets/image/icon_today_video.webp",
moreText: S.of(context).chakangengduo, moreText: S.of(context).chakangengduo,
onTap: () { onTap: () {
Navigator.of(context) Navigator.of(context).pushNamed('/router/hot_article_page');
.pushNamed('/router/hot_article_page');
}, },
), ),
hotList(), hotList(),
@ -43,9 +42,7 @@ class _HotArticle extends State<HotArticle> {
return Container( return Container(
child: ListView.builder( child: ListView.builder(
shrinkWrap: true, shrinkWrap: true,
itemCount: widget.articles != null itemCount: ((widget.articles.length > 3) ? 3 : widget.articles.length),
? ((widget.articles.length > 3) ? 3 : widget.articles.length)
: 0,
physics: NeverScrollableScrollPhysics(), physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical, scrollDirection: Axis.vertical,
padding: EdgeInsets.symmetric(vertical: 12.h), padding: EdgeInsets.symmetric(vertical: 12.h),
@ -56,7 +53,9 @@ class _HotArticle extends State<HotArticle> {
height: position == 0 ? 247.h : 96.h, height: position == 0 ? 247.h : 96.h,
margin: EdgeInsets.symmetric(vertical: 6.h, horizontal: 16.w), margin: EdgeInsets.symmetric(vertical: 6.h, horizontal: 16.w),
child: HotArticleItem( child: HotArticleItem(
article: widget.articles[position], isHot: position == 0), article: widget.articles[position],
isHot: position == 0,
),
), ),
); );
}, },

96
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/data/store.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/border_text.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/item_title.dart'; import 'package:huixiang/view_widget/item_title.dart';
@ -36,6 +37,10 @@ class _QuickOrder extends State<QuickOrder> {
@override @override
void initState() { void initState() {
apiService = ApiService(Dio(),
context: context,
token: SharedInstance.instance.token,
showLoading: false);
super.initState(); super.initState();
getLatLng(); getLatLng();
startLocation(); startLocation();
@ -60,44 +65,30 @@ class _QuickOrder extends State<QuickOrder> {
} }
getLatLng() async { getLatLng() async {
SharedPreferences.getInstance().then( apiService = ApiService(Dio(),
(value) => { context: context,
apiService = ApiService(Dio(), token: SharedInstance.instance.token,
context: context, showLoading: false);
token: value.getString('token'), if (SharedInstance.instance.latitude.isNotEmpty && SharedInstance.instance.longitude.isNotEmpty) {
showLoading: false), latLng = Position(
if (value.containsKey("latitude") && latitude: double.tryParse(SharedInstance.instance.latitude)!,
value.containsKey("longitude") ) longitude: double.tryParse(SharedInstance.instance.longitude)!,
{ timestamp: DateTime.now(),
latLng = Position( accuracy: 0,
latitude: double.tryParse(value.getString("latitude") ??"")!, altitude: 0,
longitude: double.tryParse(value.getString("longitude") ?? "")!, heading: 0,
timestamp: DateTime.now(), speed: 0,
accuracy: 0, speedAccuracy: 0
altitude: 0, );
heading: 0, queryStore(
speed: 0, SharedInstance.instance.latitude,
speedAccuracy: 0 SharedInstance.instance.longitude,
), editingController.text,
queryStore( );
value.getString("latitude"), setState(() {});
value.getString("longitude"), } else {
editingController.text, queryStore("", "", editingController.text);
), }
setState(() {
// _mapController?.updateMapOptions(
// BMFMapOptions(
// center: latLng,
// zoomLevel: 15,
// ));
})
}
else
{
queryStore("", "", editingController.text),
}
},
);
} }
startLocation() async { startLocation() async {
@ -125,11 +116,6 @@ class _QuickOrder extends State<QuickOrder> {
"${latLng?.latitude}", "${latLng?.latitude}",
"${latLng?.longitude}", "${latLng?.longitude}",
editingController.text); editingController.text);
// _mapController?.updateMapOptions(BMFMapOptions(
// center: value,
// zoomLevel: 15,
// )
// );
return r; return r;
}); });
} }
@ -137,12 +123,10 @@ class _QuickOrder extends State<QuickOrder> {
} }
saveLatLng(Position latLng, province, city, district) async { saveLatLng(Position latLng, province, city, district) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedInstance.instance.saveLatLng(latLng);
await prefs.setString("latitude", "${latLng.latitude}"); if (province != null) SharedInstance.instance.setProvince(province);
await prefs.setString("longitude", "${latLng.longitude}"); if (city != null) SharedInstance.instance.setCity(city);
if (province != null) await prefs.setString("province", province); if (district != null) SharedInstance.instance.setDistrict(district);
if (city != null) await prefs.setString("city", city);
if (district != null) await prefs.setString("district", district);
} }
@override @override
@ -267,14 +251,6 @@ class _QuickOrder extends State<QuickOrder> {
), ),
), ),
), ),
// Text(
// store?.remark ??"",
// style: TextStyle(
// fontSize: 10.sp,
// fontWeight: MyFontWeight.medium,
// color: Color(0xFF868686),
// ),
// ),
SizedBox( SizedBox(
height: 5, height: 5,
), ),
@ -386,7 +362,7 @@ class _QuickOrder extends State<QuickOrder> {
// //
// http://miniscan.lotus-wallet.com/placeorder?tenant_code=1194&table_id=1669609340031467520&store_id=1637659387134738432 // 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'); 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; return;
} }
// String result = await scanner.scan(); // String result = await scanner.scan();
@ -394,9 +370,7 @@ class _QuickOrder extends State<QuickOrder> {
String tableId = uri.queryParameters["tableId"] ?? uri.queryParameters["table_id"] ?? ""; String tableId = uri.queryParameters["tableId"] ?? uri.queryParameters["table_id"] ?? "";
String tenantCode = uri.queryParameters["tenantCode"] ?? uri.queryParameters["tenant_code"] ?? ""; String tenantCode = uri.queryParameters["tenantCode"] ?? uri.queryParameters["tenant_code"] ?? "";
String shopId = uri.queryParameters["shopId"] ?? uri.queryParameters["store_id"] ?? ""; String shopId = uri.queryParameters["shopId"] ?? uri.queryParameters["store_id"] ?? "";
if (tableId != "" && if (tableId != "" && tenantCode != "" && shopId != "") {
tenantCode != "" &&
shopId != "") {
Navigator.of(context).pushNamed( Navigator.of(context).pushNamed(
'/router/store_order', '/router/store_order',
arguments: { arguments: {

1
lib/home/home_view/shortcut_operation.dart

@ -16,7 +16,6 @@ class ShortcutOperation extends StatefulWidget {
} }
class _ShortcutOperation extends State<ShortcutOperation> { class _ShortcutOperation extends State<ShortcutOperation> {
ApiService? apiService;
@override @override
void initState() { void initState() {

31
lib/home/home_view/sign_view.dart

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/utils/font_weight.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/item_title.dart';
import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -27,29 +28,23 @@ class SignView extends StatelessWidget {
imgPath: "assets/image/icon_today_task.webp", imgPath: "assets/image/icon_today_task.webp",
moreText: S.of(context).renwuzhongxin, moreText: S.of(context).renwuzhongxin,
onTap: () { onTap: () {
SharedPreferences.getInstance().then((value) { if (SharedInstance.instance.token.isEmpty) {
if (value.getString('token') == null || LoginTipsDialog().show(context);
value.getString('token') == "") { } else {
LoginTipsDialog().show(context); Navigator.of(context).pushNamed('/router/integral_page');
} else { }
Navigator.of(context).pushNamed('/router/integral_page');
}
});
}, },
), ),
InkWell( InkWell(
onTap: () { onTap: () {
SharedPreferences.getInstance().then((value) { if (SharedInstance.instance.token.isEmpty) {
if (value.getString('token') == null || LoginTipsDialog().show(context);
value.getString('token') == "") { } else {
LoginTipsDialog().show(context); Navigator.of(context).pushNamed('/router/integral_page')
} else { .then((value) => {
Navigator.of(context).pushNamed('/router/integral_page')
.then((value) => {
if (value != null) setSigned(value), if (value != null) setSigned(value),
}); });
} }
});
}, },
child: signIn(context), child: signIn(context),
), ),

3
lib/home/home_view/top_selling_list.dart

@ -1,9 +1,11 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:huixiang/data/good_list.dart'; import 'package:huixiang/data/good_list.dart';
import 'package:huixiang/data/home_rank.dart'; import 'package:huixiang/data/home_rank.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/app_util.dart'; import 'package:huixiang/utils/app_util.dart';
import 'package:huixiang/utils/flutter_utils.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:huixiang/view_widget/custom_image.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/utils/font_weight.dart';
@ -26,6 +28,7 @@ class _TopSellingList extends State<TopSellingList> {
@override @override
void initState() { void initState() {
apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
super.initState(); super.initState();
} }

1
lib/home/home_view/union_entry.dart

@ -17,7 +17,6 @@ class UnionEntry extends StatefulWidget {
} }
class _UnionEntry extends State<UnionEntry> { class _UnionEntry extends State<UnionEntry> {
ApiService? apiService;
@override @override
void initState() { void initState() {

1
lib/home/home_view/welfare_core.dart

@ -13,7 +13,6 @@ class WelfareCore extends StatefulWidget {
} }
class _WelfareCore extends State<WelfareCore> { class _WelfareCore extends State<WelfareCore> {
ApiService? apiService;
@override @override
void initState() { void initState() {

16
lib/home/huixiang_brand_page.dart

@ -13,6 +13,7 @@ import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/main.dart'; import 'package:huixiang/main.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.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/classic_header.dart';
import 'package:huixiang/view_widget/store_title_tab.dart'; import 'package:huixiang/view_widget/store_title_tab.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
@ -28,8 +29,7 @@ class BrandPage extends StatefulWidget {
} }
} }
class _BrandPage extends State<BrandPage> class _BrandPage extends State<BrandPage> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
final ScrollController scrollController = ScrollController(); final ScrollController scrollController = ScrollController();
final RefreshController refreshController = RefreshController(); final RefreshController refreshController = RefreshController();
@ -45,17 +45,16 @@ class _BrandPage extends State<BrandPage>
msg: S.current.zhengzaijiazai, msg: S.current.zhengzaijiazai,
); );
final SharedPreferences value = await SharedPreferences.getInstance();
apiService = ApiService( apiService = ApiService(
Dio(), Dio(),
context: context, context: context,
token: value.getString('token'), token: SharedInstance.instance.token,
); );
BaseData<BrandData>? baseData = BaseData<BrandData>? baseData =
await apiService?.queryHome().catchError((error) { await apiService?.queryHome().catchError((error) {
refreshController.refreshFailed(); refreshController.refreshFailed();
return Future.value(null); return BaseData<BrandData>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
brandData = baseData!.data; brandData = baseData!.data;
@ -67,22 +66,21 @@ class _BrandPage extends State<BrandPage>
"model": {"type": "BRAND_APP"}, "model": {"type": "BRAND_APP"},
}).catchError((error) { }).catchError((error) {
refreshController.refreshFailed(); refreshController.refreshFailed();
return Future.value(null); return BaseData<PageInfo<BannerData>>()..isSuccess = false;
}); });
bannerData.clear(); bannerData.clear();
bannerData.addAll(banner?.data?.records ?? []); bannerData.addAll(banner?.data?.records ?? []);
BaseData? brand = await apiService?.queryHomeBrand().catchError((error) { BaseData? brand = await apiService?.queryHomeBrand().catchError((error) {
refreshController.refreshFailed(); refreshController.refreshFailed();
return Future.value(null); return BaseData()..isSuccess = false;
}); });
if (brand?.isSuccess ?? false) { if (brand?.isSuccess ?? false) {
brands.clear(); brands.clear();
globaKeys.clear(); globaKeys.clear();
brands.addAll((brand!.data["brandList"] as List<dynamic>?) brands.addAll((brand!.data["brandList"] as List<dynamic>?)
?.map((e) => Brand.fromJson(e)) ?.map((e) => Brand.fromJson(e))
.toList() ?? .toList() ?? []);
[]);
founder = Founder.fromJson(brand.data["founder"]); founder = Founder.fromJson(brand.data["founder"]);
brands.forEach((element) { brands.forEach((element) {
globaKeys.add(GlobalKey()); globaKeys.add(GlobalKey());

36
lib/home/huixiang_view/huixiang_banner.dart

@ -69,20 +69,26 @@ class _HuiXiangBanner extends State<HuiXiangBanner> {
bannerClick(BannerData bannerData) async { bannerClick(BannerData bannerData) async {
switch (bannerData.contentType) { switch (bannerData.contentType) {
case 1: case 1:
Navigator.of(context).pushNamed('/router/integral_store_page', Navigator.of(context).pushNamed(
arguments: {"goodsId": bannerData.content}); '/router/integral_store_page',
arguments: {"goodsId": bannerData.content},
);
break; break;
case 2: case 2:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page',
"activityId": bannerData.content, arguments: {
}); "activityId": bannerData.content,
},
);
break; break;
case 3: case 3:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page',
"articleId": bannerData.content, arguments: {
}); "articleId": bannerData.content,
},
);
break; break;
case 4: case 4:
String? router = bannerData.content; String? router = bannerData.content;
@ -99,10 +105,12 @@ class _HuiXiangBanner extends State<HuiXiangBanner> {
} }
break; break;
case 5: case 5:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/class_details', arguments: { '/router/class_details',
"id": bannerData.content, arguments: {
}); "id": bannerData.content,
},
);
break; break;
case 7: case 7:
String? router = bannerData.content; String? router = bannerData.content;

1
lib/home/huixiang_view/origin_info.dart

@ -308,4 +308,5 @@ class _OriginInfo extends State<OriginInfo> {
), ),
); );
} }
} }

23
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/main.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
@ -68,6 +69,8 @@ class _PointsMallPage extends State<PointsMallPage>
List<BannerData> bannerData = []; List<BannerData> bannerData = [];
queryUser() async { queryUser() async {
client ??= ApiService(Dio(), context: context, token: SharedInstance.instance.token, showLoading: false);
BaseData<PageInfo<BannerData>>? banner = await client?.queryBanner({ BaseData<PageInfo<BannerData>>? banner = await client?.queryBanner({
"model": {"type": "CREDIT_INDEX"}, "model": {"type": "CREDIT_INDEX"},
}).catchError((onError) { }).catchError((onError) {
@ -82,11 +85,9 @@ class _PointsMallPage extends State<PointsMallPage>
BaseData<UserInfo>? baseData = await client?.queryInfo().catchError((onError) { BaseData<UserInfo>? baseData = await client?.queryInfo().catchError((onError) {
return BaseData<UserInfo>()..isSuccess = false; return BaseData<UserInfo>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if ((baseData?.isSuccess ?? false) && baseData?.data != null) {
userInfo = baseData!.data; userInfo = baseData!.data;
SharedPreferences.getInstance().then((value) => { SharedInstance.instance.saveUser(baseData.data!);
value.setString('user', jsonEncode(baseData.data)),
});
} }
} }
@ -95,8 +96,7 @@ class _PointsMallPage extends State<PointsMallPage>
msg: S.current.zhengzaijiazai, msg: S.current.zhengzaijiazai,
); );
final SharedPreferences value = await SharedPreferences.getInstance(); client = ApiService(Dio(), context: context, token: SharedInstance.instance.token, showLoading: false);
client = ApiService(Dio(), context: context, token: value.getString('token'), showLoading: false);
await queryUser(); await queryUser();
@ -221,11 +221,12 @@ class _PointsMallPage extends State<PointsMallPage>
} }
_toDetails(index) async { _toDetails(index) async {
await Navigator.of(context).pushNamed('/router/integral_store_page', await Navigator.of(context).pushNamed(
arguments: {"goodsId": goods[index].id}); '/router/integral_store_page',
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); arguments: {"goodsId": goods[index].id},
String? token = sharedPreferences.getString("token"); );
if (token?.isNotEmpty ?? false) queryUser(); String token = SharedInstance.instance.token;
if (token.isNotEmpty) queryUser();
} }
@override @override

14
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/generated/l10n.dart';
import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/data/user_info.dart';
import 'package:huixiang/utils/font_weight.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/custom_image.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
@ -22,13 +23,12 @@ class _PointMallUser extends State<PointMallUser> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return InkWell( return InkWell(
onTap: () { onTap: () {
SharedPreferences.getInstance().then((value) { if (SharedInstance.instance.token.isEmpty) {
if (value.getString("token") == null || Navigator.of(context).pushNamed(
value.getString("token") == "") { '/router/new_login_page',
Navigator.of(context).pushNamed('/router/new_login_page', arguments: {"login": "login"},
arguments: {"login": "login"}); );
} }
});
}, },
child: Container( child: Container(
margin: EdgeInsets.all(16), margin: EdgeInsets.all(16),

5
lib/home/points_mall_view/points_goods_title.dart

@ -23,8 +23,8 @@ class PointsGoodsTitle extends StatefulWidget {
} }
} }
class _PointsGoodsTitle extends State<PointsGoodsTitle> class _PointsGoodsTitle extends State<PointsGoodsTitle> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin{
with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin{
var _itemText = S.current.morenpaixu; var _itemText = S.current.morenpaixu;
List<String> sortString = [ List<String> sortString = [
S.current.morenpaixu, S.current.morenpaixu,
@ -39,6 +39,7 @@ class _PointsGoodsTitle extends State<PointsGoodsTitle>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
return Container( return Container(
margin: EdgeInsets.only(top:24.h), margin: EdgeInsets.only(top:24.h),
child: Column( child: Column(

3
lib/home/points_mall_view/points_goods_view.dart

@ -20,6 +20,7 @@ class PointGoods extends StatefulWidget {
} }
class _PointGoods extends State<PointGoods> { class _PointGoods extends State<PointGoods> {
String pointPrice(Goods goods) { String pointPrice(Goods goods) {
if (goods.oneBean != "0") { if (goods.oneBean != "0") {
return "${goods.oneBean}印章"; return "${goods.oneBean}印章";
@ -96,7 +97,7 @@ class _PointGoods extends State<PointGoods> {
offset: Offset(0, 3), offset: Offset(0, 3),
blurRadius: 14, blurRadius: 14,
spreadRadius: 0, spreadRadius: 0,
) ),
], ],
color: Colors.white, color: Colors.white,
), ),

33
lib/home/points_mall_view/points_mall_banner.dart

@ -73,20 +73,24 @@ class _PointMallBanner extends State<PointMallBanner> {
bannerClick(BannerData bannerData) async { bannerClick(BannerData bannerData) async {
switch (bannerData.contentType) { switch (bannerData.contentType) {
case 1: case 1:
Navigator.of(context).pushNamed('/router/integral_store_page', Navigator.of(context).pushNamed(
arguments: {"goodsId": bannerData.content}); '/router/integral_store_page',
arguments: {"goodsId": bannerData.content},
);
break; break;
case 2: case 2:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page', arguments: {
"activityId": bannerData.content, "activityId": bannerData.content,
}); },
);
break; break;
case 3: case 3:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/web_page', arguments: { '/router/web_page', arguments: {
"articleId": bannerData.content, "articleId": bannerData.content,
}); },
);
break; break;
case 4: case 4:
String? router = bannerData.content; String? router = bannerData.content;
@ -103,10 +107,11 @@ class _PointMallBanner extends State<PointMallBanner> {
} }
break; break;
case 5: case 5:
Navigator.of(context) Navigator.of(context).pushNamed(
.pushNamed('/router/class_details', arguments: { '/router/class_details', arguments: {
"id": bannerData.content, "id": bannerData.content,
}); },
);
break; break;
case 7: case 7:
String? router = bannerData.content; String? router = bannerData.content;

8
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/data/base_data.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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_appbar.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -29,11 +30,8 @@ class _TradingCardPage extends State<TradingCardPage> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) { apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = queryUserBalance();
ApiService(Dio(), context: context, token: value.getString("token"));
queryUserBalance();
});
} }
@override @override

36
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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
@ -54,25 +55,20 @@ class _WelfareExchange extends State<WelfareExchange>
@override @override
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(Dio(),
apiService = ApiService(Dio(), context: context,
context: context, token: SharedInstance.instance.token,
token: value.getString("token"), showLoading: false);
showLoading: false), creditGoods();
creditGoods(),
});
} }
queryUser() async { queryUser() async {
BaseData<UserInfo>? baseData = BaseData<UserInfo>? baseData = await apiService?.queryInfo().catchError((onError) {
await apiService?.queryInfo().catchError((onError) {
return BaseData<UserInfo>()..isSuccess = false; return BaseData<UserInfo>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if ((baseData?.isSuccess ?? false) && baseData!.data != null) {
userInfo = baseData!.data; userInfo = baseData.data;
SharedPreferences.getInstance().then((value) => { SharedInstance.instance.saveUser(baseData.data!);
value.setString('user', jsonEncode(baseData.data)),
});
} }
} }
@ -82,11 +78,9 @@ class _WelfareExchange extends State<WelfareExchange>
SmartDialog.showLoading( SmartDialog.showLoading(
msg: S.current.zhengzaijiazai, msg: S.current.zhengzaijiazai,
); );
final SharedPreferences value = await SharedPreferences.getInstance();
apiService = ApiService(Dio(), apiService = ApiService(Dio(),
context: context, context: context,
token: value.getString('token'), token: SharedInstance.instance.token,
showLoading: false); showLoading: false);
await queryUser(); await queryUser();
@ -106,8 +100,7 @@ class _WelfareExchange extends State<WelfareExchange>
gooods.addAll(goodsData?.data?.list ?? []); gooods.addAll(goodsData?.data?.list ?? []);
} }
BaseData<PageInfo<GoodsCategory>>? dataCategory = BaseData<PageInfo<GoodsCategory>>? dataCategory = await apiService?.goodsCategory({
await apiService?.goodsCategory({
"current": 1, "current": 1,
"map": {}, "map": {},
"model": {"pageNum": 1, "pageSize": 20, "searchKey": ""}, "model": {"pageNum": 1, "pageSize": 20, "searchKey": ""},
@ -135,8 +128,7 @@ class _WelfareExchange extends State<WelfareExchange>
"pageSize": 100, "pageSize": 100,
"state": 1 "state": 1
}; };
BaseData<PageInfo<Goods>>? pageGoods = BaseData<PageInfo<Goods>>? pageGoods = await apiService?.creditGoods(param).catchError((onError) {
await apiService?.creditGoods(param).catchError((onError) {
refreshController.loadFailed(); refreshController.loadFailed();
refreshController.refreshFailed(); refreshController.refreshFailed();
return BaseData<PageInfo<Goods>>()..isSuccess = false; return BaseData<PageInfo<Goods>>()..isSuccess = false;
@ -465,7 +457,7 @@ class _WelfareExchange extends State<WelfareExchange>
Widget pointList() { Widget pointList() {
return Container( return Container(
child: (goods?.isEmpty ?? true) child: (goods.isEmpty)
? NoDataView( ? NoDataView(
src: "assets/image/xiao_fei.webp", src: "assets/image/xiao_fei.webp",
isShowBtn: false, isShowBtn: false,

72
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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
@ -51,16 +52,12 @@ class _WelfarePage extends State<WelfarePage> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
if (apiService == null) { apiService = ApiService(
SharedPreferences.getInstance().then((value) { Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString("token"), _onRefresh();
);
_onRefresh();
});
}
} }
queryGoods() async { queryGoods() async {
@ -73,11 +70,10 @@ class _WelfarePage extends State<WelfarePage> {
"pageSize": 100, "pageSize": 100,
"state": 1 "state": 1
}; };
BaseData<PageInfo<Goods>>? pageGoods = BaseData<PageInfo<Goods>>? pageGoods = await apiService?.creditGoods(param).catchError((onError) {
await apiService?.creditGoods(param).catchError((onError) {
refreshController.loadFailed(); refreshController.loadFailed();
refreshController.refreshFailed(); refreshController.refreshFailed();
return Future.value(null); return BaseData<PageInfo<Goods>>()..isSuccess = false;
}); });
SmartDialog.dismiss(); SmartDialog.dismiss();
if (pageGoods?.isSuccess ?? false) { if (pageGoods?.isSuccess ?? false) {
@ -98,9 +94,7 @@ class _WelfarePage extends State<WelfarePage> {
"searchKey": "", "searchKey": "",
"state": 0 "state": 0
}).catchError((onError) { }).catchError((onError) {
SmartDialog.showToast(AppUtils.dioErrorTypeToString(onError.type), return BaseData<PageInfo<Coupon>>()..isSuccess = false;
alignment: Alignment.center);
return Future.value(null);
}); });
coupons.clear(); coupons.clear();
coupon.clear(); coupon.clear();
@ -158,9 +152,10 @@ class _WelfarePage extends State<WelfarePage> {
height: 236.h, height: 236.h,
), ),
Expanded( Expanded(
child: Container( child: Container(
color: Colors.white, color: Colors.white,
)) ),
)
], ],
), ),
Scaffold( Scaffold(
@ -219,7 +214,7 @@ class _WelfarePage extends State<WelfarePage> {
benefitExchange(), benefitExchange(),
], ],
), ),
) ),
// activityTask(), // activityTask(),
], ],
), ),
@ -445,8 +440,7 @@ class _WelfarePage extends State<WelfarePage> {
style: TextStyle( style: TextStyle(
fontSize: 16.sp, fontSize: 16.sp,
fontWeight: MyFontWeight.medium, fontWeight: MyFontWeight.medium,
color: color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
), ),
), ),
SizedBox( SizedBox(
@ -457,8 +451,7 @@ class _WelfarePage extends State<WelfarePage> {
style: TextStyle( style: TextStyle(
fontSize: 24.sp, fontSize: 24.sp,
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
), ),
), ),
], ],
@ -488,8 +481,7 @@ class _WelfarePage extends State<WelfarePage> {
style: TextStyle( style: TextStyle(
fontSize: 22.sp, fontSize: 22.sp,
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
), ),
), ),
], ],
@ -520,8 +512,7 @@ class _WelfarePage extends State<WelfarePage> {
style: TextStyle( style: TextStyle(
fontSize: 26.sp, fontSize: 26.sp,
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
), ),
), ),
], ],
@ -552,8 +543,7 @@ class _WelfarePage extends State<WelfarePage> {
style: TextStyle( style: TextStyle(
fontSize: 16.sp, fontSize: 16.sp,
fontWeight: MyFontWeight.medium, fontWeight: MyFontWeight.medium,
color: color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
), ),
), ),
SizedBox( SizedBox(
@ -566,8 +556,7 @@ class _WelfarePage extends State<WelfarePage> {
style: TextStyle( style: TextStyle(
fontSize: 24.sp, fontSize: 24.sp,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
), ),
), ),
], ],
@ -591,8 +580,7 @@ class _WelfarePage extends State<WelfarePage> {
style: TextStyle( style: TextStyle(
fontSize: 30.sp, fontSize: 30.sp,
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
), ),
), ),
SizedBox( SizedBox(
@ -603,8 +591,7 @@ class _WelfarePage extends State<WelfarePage> {
style: TextStyle( style: TextStyle(
fontSize: 16.sp, fontSize: 16.sp,
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: color: cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
cop.status == 3 ? Color(0xFFB3B3B3) : Color(0xff32A060),
), ),
), ),
], ],
@ -693,7 +680,9 @@ class _WelfarePage extends State<WelfarePage> {
/// ///
receiveCoupon(couponId) async { receiveCoupon(couponId) async {
couponIndex = swiperIndex; couponIndex = swiperIndex;
BaseData? baseData = await apiService?.receiveCoupon(couponId); BaseData? baseData = await apiService?.receiveCoupon(couponId).catchError((error){
return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
queryCoupon(); queryCoupon();
showAlertDialog(); showAlertDialog();
@ -805,7 +794,7 @@ class _WelfarePage extends State<WelfarePage> {
Icons.keyboard_arrow_right, Icons.keyboard_arrow_right,
color: Color(0xFF4D4D4D), color: Color(0xFF4D4D4D),
size: 20, size: 20,
) ),
], ],
), ),
), ),
@ -833,8 +822,7 @@ class _WelfarePage extends State<WelfarePage> {
//Widget之间间距 //Widget之间间距
mainAxisSpacing: 16.w, mainAxisSpacing: 16.w,
//Widget宽高比例 0.59 //Widget宽高比例 0.59
childAspectRatio: 200 / childAspectRatio: 200 / (285 / 2 + (285 / 2) * AppUtils.textScale(context)),
(285 / 2 + (285 / 2) * AppUtils.textScale(context)),
), ),
itemBuilder: (context, index) { itemBuilder: (context, index) {
return GestureDetector( return GestureDetector(
@ -847,7 +835,7 @@ class _WelfarePage extends State<WelfarePage> {
child: exchangeItem(goods[index]), child: exchangeItem(goods[index]),
); );
}, },
) ),
], ],
), ),
); );
@ -865,7 +853,7 @@ class _WelfarePage extends State<WelfarePage> {
offset: Offset(0, 2), offset: Offset(0, 2),
blurRadius: 4, blurRadius: 4,
spreadRadius: 0, spreadRadius: 0,
) ),
], ],
), ),
child: Stack( child: Stack(

9
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/auth.pb.dart';
import 'package:huixiang/im/out/message.pb.dart'; import 'package:huixiang/im/out/message.pb.dart';
import 'package:huixiang/main.dart'; import 'package:huixiang/main.dart';
import 'package:huixiang/utils/shared_preference.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart'; import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
class SocketClient { class SocketClient {
Socket? _socket; Socket? _socket;
SharedPreferences? _shared;
Timer? timer; Timer? timer;
bool get heartbeatActive => timer != null && timer!.isActive; bool get heartbeatActive => timer != null && timer!.isActive;
connect() async { connect() async {
_shared = await SharedPreferences.getInstance();
if (_socket != null) { if (_socket != null) {
reconnect(); reconnect();
@ -50,11 +49,9 @@ class SocketClient {
Message message = Message.fromJson(messageMap); Message message = Message.fromJson(messageMap);
if (callbacks[dataResult.from] != null) { if (callbacks[dataResult.from] != null) {
callbacks[dataResult.from]?.call(message); callbacks[dataResult.from]?.call(message);
/// user conversation callback /// user conversation callback
} }
callbacks[userId]?.call(message); callbacks[userId]?.call(message);
/// user self conversation list callback /// user self conversation list callback
}); });
}); });
@ -66,7 +63,7 @@ class SocketClient {
debugPrint("socket-listen-down: down"); debugPrint("socket-listen-down: down");
}); });
authRequest(_shared?.getString("token") ?? ""); authRequest(SharedInstance.instance.token);
heartbeat(); heartbeat();
}).catchError((error) { }).catchError((error) {
@ -257,5 +254,5 @@ class SocketClient {
return true; return true;
} }
String get userId => _shared?.getString("userId") ?? ""; String get userId => SharedInstance.instance.userId;
} }

1
lib/im/add_friend.dart

@ -17,7 +17,6 @@ class AddFriend extends StatefulWidget {
} }
class _AddFriend extends State<AddFriend> { class _AddFriend extends State<AddFriend> {
ApiService? apiService;
@override @override
void initState() { void initState() {

534
lib/im/chat_details_page.dart

@ -1,29 +1,30 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'dart:ui';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.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_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/base_data.dart';
import 'package:huixiang/data/im_user.dart';
import 'package:huixiang/data/user_info.dart'; import 'package:huixiang/data/user_info.dart';
import 'package:huixiang/im/database/message.dart'; import 'package:huixiang/im/database/message.dart';
import 'package:huixiang/im/out/message.pb.dart'; import 'package:huixiang/im/out/message.pb.dart';
import 'package:huixiang/main.dart'; import 'package:huixiang/main.dart';
import 'package:huixiang/data/im_user.dart';
import 'package:huixiang/retrofit/retrofit_api.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/classic_header.dart';
import 'package:huixiang/view_widget/my_appbar.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:image_pickers/image_pickers.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../community/release_dynamic.dart'; import '../../community/release_dynamic.dart';
import '../../generated/l10n.dart'; import '../../generated/l10n.dart';
@ -31,8 +32,7 @@ import '../../utils/font_weight.dart';
import '../utils/flutter_utils.dart'; import '../utils/flutter_utils.dart';
import '../view_widget/custom_image.dart'; import '../view_widget/custom_image.dart';
import '../view_widget/request_permission.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 { class ChatDetailsPage extends StatefulWidget {
final Map<String, dynamic>? arguments; final Map<String, dynamic>? arguments;
@ -46,43 +46,39 @@ class ChatDetailsPage extends StatefulWidget {
} }
class _ChatDetailsPage extends State<ChatDetailsPage> class _ChatDetailsPage extends State<ChatDetailsPage>
with WidgetsBindingObserver with WidgetsBindingObserver {
implements OnChatMessage {
ApiService? apiService; ApiService? apiService;
List<Medias> mediaPaths = []; List<Medias> mediaPaths = [];
int selectCount = 9; int selectCount = 9;
int dynamicType = 0; int dynamicType = 0;
final TextEditingController chatController = TextEditingController(); final TextEditingController chatController = TextEditingController();
bool emojiShowing = false;
double keyboard = -1;
bool needShowSmiley = false;
bool needHideSmiley = false;
bool isKeyBoardShow = false; bool isKeyBoardShow = false;
bool emojiShowing = false;
bool moreShow = false; bool moreShow = false;
bool needShowMore = false;
bool needHideMore = false; double keyboard = -1;
var commentFocus = FocusNode(); var commentFocus = FocusNode();
String hintText = "输入消息内容..."; String hintText = "输入消息内容...";
UserInfo? userInfo; UserInfo? userInfo;
final OnChatMessage? _tempOnChatMessage = OnChatMsgInstance.instance.onChatMessage; // final OnChatMessage? _tempOnChatMessage = OnChatMsgInstance.instance.onChatMessage;
final ScrollController scrollController = ScrollController(); final ScrollController scrollController = ScrollController();
GlobalKey<AnimatedListState> animatedListKey = GlobalKey<AnimatedListState>();
String tex = ""; String tex = "";
String selfUserId = ""; String selfUserId = "";
ImUser? _toUser; ImUser? _toUser;
late String conversation; late String conversation;
List<String> imageUrl = []; List<String> imageUrl = [];
@override double inputWidgetHeight = 95;
void onMessage(txt) { double dynamicInputHeight = 0;
// SmartDialog.showToast("聊天 $txt", alignment: Alignment.center);
}
RefreshController refreshController = RefreshController(); RefreshController refreshController = RefreshController();
List<Message> messages = []; List<Message> messages = [];
int page = 0; int page = 0;
loadMessageList() async { loadMessageList() async {
selfUserId = (await SharedPreferences.getInstance()).getString("userId") ?? ""; selfUserId = SharedInstance.instance.userId;
debugPrint("selfUserId: $selfUserId _toUser?.mid: ${_toUser?.mid} ");
conversation = conversationId(selfUserId, _toUser?.mid); conversation = conversationId(selfUserId, _toUser?.mid);
ImUser? imUser = await hxDatabase.queryImUserById(conversation); ImUser? imUser = await hxDatabase.queryImUserById(conversation);
@ -95,9 +91,10 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
await refresh(); await refresh();
socketClient.addCallback(_toUser?.mid ?? '', (Message message) { socketClient.addCallback(_toUser?.mid ?? '', (Message message) {
messages.insert(0, message); messages.add(message);
if (message.msgType == MsgType.VIDEO.value || message.msgType == MsgType.IMAGE.value) { animatedListKey.currentState?.insertItem(messages.length - 1);
imageUrl.add(message.attach); if ((message.msgType == MsgType.VIDEO.value || message.msgType == MsgType.IMAGE.value) && (message.attach?.isNotEmpty ?? false)) {
imageUrl.add(message.attach!);
} }
messageShowTime().then((value) { messageShowTime().then((value) {
refreshState(); refreshState();
@ -107,66 +104,69 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
messageImageUrl(); messageImageUrl();
refreshState(); // refreshState();
jumpToBottom(); // jumpToBottom();
} }
Future refresh() async { Future<double> refresh() async {
List<Message>? messagePage = await hxDatabase.queryUList(conversation, page: page + 1, pageSize: 10); List<Message>? messagePage = await hxDatabase.queryUList(conversation, page: page + 1, pageSize: 10);
debugPrint("refresh-message-list: ${messagePage?.length ?? ''} page: $page"); debugPrint("refresh-message-list: ${messagePage?.length ?? ''} page: $page");
if (messagePage?.isEmpty ?? true) { if (messagePage?.isEmpty ?? true) {
refreshController.loadNoData(); refreshController.refreshCompleted();
return; return 0;
} else { } else {
refreshController.loadComplete(); refreshController.refreshCompleted();
page += 1; 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) { if (page == 1) {
messages = messagePage!; messages.addAll(messagePage.reversed.toList());
animatedListKey.currentState?.insertAllItems(0, messagePage.length);
} else { } else {
messages.addAll(messagePage!); messages.insertAll(0, messagePage.reversed.toList());
animatedListKey.currentState?.insertAllItems(0, messagePage.length, duration: 300.milliseconds);
} }
await messageShowTime(); await messageShowTime();
return Future.value(); return height;
} }
/// ///
messageImageUrl() { 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 { Future messageShowTime() async {
List<Message>? messagePages = await hxDatabase.queryTList(conversation); List<Message>? messagePages = await hxDatabase.queryTList(conversation);
for (var value in messages) { 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; value.showTime = message != null;
} }
} }
SharedPreferences? sharedPre;
/// ///
queryUser() async { queryUser() async {
sharedPre = await SharedPreferences.getInstance(); apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
if (apiService == null)
apiService = ApiService(Dio(), context: context, token: sharedPre?.getString("token")); userInfo = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson));
if ((sharedPre?.containsKey('user') ?? false) && if (userInfo?.phone?.isNotEmpty ?? false) {
sharedPre?.getString('user') != null && setState(() {});
sharedPre?.getString('user') != "") { return;
userInfo = UserInfo.fromJson(jsonDecode(sharedPre!.getString('user')!));
if (userInfo?.phone?.isNotEmpty ?? false) {
setState(() {});
return;
}
} }
BaseData<UserInfo>? baseData = await apiService?.queryInfo().catchError((onError) {}); BaseData<UserInfo>? baseData = await apiService?.queryInfo().catchError((onError) {
if (baseData?.isSuccess ?? false) { return BaseData<UserInfo>()..isSuccess = false;
});
if ((baseData?.isSuccess ?? false) && baseData?.data != null) {
setState(() { setState(() {
userInfo = baseData!.data; userInfo = baseData!.data;
}); });
SharedPreferences.getInstance().then((value) => { SharedInstance.instance.saveUser(baseData!.data!);
value.setString('user', jsonEncode(baseData!.data)),
});
} }
} }
@ -174,75 +174,93 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
if (mounted) setState(() {}); if (mounted) setState(() {});
} }
late StreamSubscription<bool> keyboardSubscription;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_toUser = widget.arguments?["toUser"]; _toUser = widget.arguments?["toUser"];
OnChatMsgInstance.instance.onChatMessage = this; // OnChatMsgInstance.instance.onChatMessage = this;
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
commentFocus.addListener(_focusNodeListener); commentFocus.addListener(_focusNodeListener);
queryUser(); queryUser();
loadMessageList(); loadMessageList();
}
void jumpToBottom() { scrollController.addListener(() {
Future.delayed(const Duration(milliseconds: 100), () { debugPrint("scrollController-onChange: ${scrollController.position.pixels}");
scrollController.position.jumpTo(0); if (messages.length >= 10 && scrollController.position.pixels < -80) {
if (!loading) {
loading = true;
refresh().then((value) => loading = false);
}
}
}); });
}
void didChangeMetrics() { var keyboardVisibilityController = KeyboardVisibilityController();
WidgetsBinding.instance.addPostFrameCallback((_) { keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) {
if (!mounted) return; isKeyBoardShow = visible;
isKeyBoardShow = MediaQuery.of(context).viewInsets.bottom > 0; debugPrint("keyboardVisibility-onChange: ${isKeyBoardShow}");
if (MediaQuery.of(context).viewInsets.bottom == 0) { if (isKeyBoardShow) {
if (isKeyBoardShow) { if (!emojiShowing && !moreShow) {
FocusScope.of(context).requestFocus(FocusNode()); chatController.clear();
if (mounted) if (!emojiShowing) if (!moreShow)
setState(() {
hintText = "请输入消息内容...";
isKeyBoardShow = false;
});
} }
} else { } else {
if (mounted) inputWidgetHeight = 95;
setState(() {
isKeyBoardShow = true;
});
} }
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(() { bool loading = false;
emojiShowing = true;
}); void jumpToBottom() {
} Future.delayed(const Duration(milliseconds: 400), () {
if (needHideSmiley && window.viewInsets.bottom > 0.1) { if (scrollController.hasClients && scrollController.position.pixels != scrollController.position.maxScrollExtent) {
needHideSmiley = false; scrollController.position.animateTo(scrollController.position.maxScrollExtent, duration: 250.milliseconds, curve: Curves.easeInOut);
setState(() { }
emojiShowing = false; });
}); }
}
if (needShowMore && window.viewInsets.bottom <= 0.1) { @override
needShowMore = false; void didChangeMetrics() {
setState(() { super.didChangeMetrics();
moreShow = true; dynamicInputHeight = MediaQuery.of(context).viewInsets.bottom;
}); if (dynamicInputHeight > 0 && dynamicInputHeight > keyboard) {
} keyboard = dynamicInputHeight;
if (needHideMore && window.viewInsets.bottom > 0.1) {
needHideMore = false;
setState(() {
moreShow = false;
});
} }
} }
@override @override
void dispose() { void dispose() {
super.dispose(); super.dispose();
OnChatMsgInstance.instance.onChatMessage = _tempOnChatMessage; // OnChatMsgInstance.instance.onChatMessage = _tempOnChatMessage;
keyboardSubscription.cancel();
WidgetsBinding.instance.removeObserver(this); WidgetsBinding.instance.removeObserver(this);
commentFocus.removeListener(_focusNodeListener); commentFocus.removeListener(_focusNodeListener);
scrollController.dispose(); scrollController.dispose();
@ -260,39 +278,51 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
/// ///
_onTextFieldTap() { _onTextFieldTap() {
if (emojiShowing) { if (emojiShowing) {
needHideSmiley = true; emojiShowing = false;
} }
if (moreShow) { if (moreShow) {
needHideMore = true; moreShow = false;
} }
} }
/// ///
_onSmileyTap() { _onSmileyTap() {
if (!emojiShowing && commentFocus.hasFocus && isKeyBoardShow) { emojiShowing = !emojiShowing;
needShowSmiley = true; if (isKeyBoardShow && commentFocus.hasFocus) {
commentFocus.unfocus(); commentFocus.unfocus();
}
if (moreShow) {
moreShow = false;
}
if (emojiShowing) {
if (inputWidgetHeight == 95) {
inputWidgetHeight += (keyboard == -1 ? 270 : keyboard);
jumpToBottom();
}
} else { } else {
setState(() { inputWidgetHeight = 95;
emojiShowing = !emojiShowing;
isKeyBoardShow = emojiShowing;
moreShow = false;
});
} }
setState(() {});
} }
/// ///
_onMoreTap() { _onMoreTap() {
if (!moreShow && commentFocus.hasFocus && isKeyBoardShow) { moreShow = !moreShow;
needShowMore = true; if (isKeyBoardShow && commentFocus.hasFocus) {
commentFocus.unfocus(); commentFocus.unfocus();
}
if (emojiShowing) {
emojiShowing = false;
}
if (moreShow) {
if (inputWidgetHeight == 95) {
inputWidgetHeight += (keyboard == -1 ? 167 : keyboard);
jumpToBottom();
}
} else { } else {
setState(() { inputWidgetHeight = 95;
moreShow = !moreShow;
isKeyBoardShow = moreShow;
emojiShowing = false;
});
} }
setState(() {});
} }
//// ////
@ -330,7 +360,8 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
String fileUrl = await qiniu.uploadFile(apiService!, path); String fileUrl = await qiniu.uploadFile(apiService!, path);
socketClient.sendMessage(_toUser?.mid ?? '', fileUrl, attach: path, msgType: galleryMode == GalleryMode.image ? 2 : 4).then((value) { socketClient.sendMessage(_toUser?.mid ?? '', fileUrl, attach: path, msgType: galleryMode == GalleryMode.image ? 2 : 4).then((value) {
Message message = value; Message message = value;
messages.insert(0, message); messages.add(message);
animatedListKey.currentState?.insertItem(messages.length - 1);
chatController.clear(); chatController.clear();
messageShowTime().then((value) { messageShowTime().then((value) {
refreshState(); refreshState();
@ -394,7 +425,8 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
String fileUrl = await qiniu.uploadFile(apiService!, path); String fileUrl = await qiniu.uploadFile(apiService!, path);
socketClient.sendMessage(_toUser?.mid ?? '', fileUrl, attach: path, msgType: 2).then((value) { socketClient.sendMessage(_toUser?.mid ?? '', fileUrl, attach: path, msgType: 2).then((value) {
Message message = value; Message message = value;
messages.insert(0, message); messages.add(message);
animatedListKey.currentState?.insertItem(messages.length - 1);
chatController.clear(); chatController.clear();
messageShowTime().then((value) { messageShowTime().then((value) {
refreshState(); refreshState();
@ -485,29 +517,21 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext ctx) {
double h = MediaQuery.of(context).viewInsets.bottom;
if (h > 0) {
jumpToBottom();
if (keyboard < h) {
keyboard = h;
// setState(() {});
}
}
return GestureDetector( return GestureDetector(
behavior: HitTestBehavior.translucent, behavior: HitTestBehavior.translucent,
onTap: () { onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
setState(() { setState(() {
needShowSmiley = false;
emojiShowing = false; emojiShowing = false;
isKeyBoardShow = emojiShowing; isKeyBoardShow = false;
moreShow = false; moreShow = false;
isKeyBoardShow = moreShow;
}); });
inputWidgetHeight = 95;
FocusScope.of(context).requestFocus(FocusNode());
// jumpToBottom();
}, },
child: Scaffold( child: Scaffold(
// resizeToAvoidBottomInset: false, resizeToAvoidBottomInset: true,
backgroundColor: Color(0xFFF6F6F6), backgroundColor: Color(0xFFF6F6F6),
appBar: MyAppBar( appBar: MyAppBar(
title: _toUser?.nickname, title: _toUser?.nickname,
@ -515,11 +539,16 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
titleSize: 17.sp, titleSize: 17.sp,
leading: true, leading: true,
leadingColor: Colors.black, leadingColor: Colors.black,
toolbarHeight: kToolbarHeight,
action: GestureDetector( action: GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () async { onTap: () async {
await Navigator.of(context).pushNamed('/router/chat_setting', await Navigator.of(context).pushNamed(
arguments: {"userId": _toUser?.mid}); '/router/chat_setting',
arguments: {
"userId": _toUser?.mid,
},
);
page = 0; page = 0;
refresh().then((value) { refresh().then((value) {
refreshState(); refreshState();
@ -536,32 +565,11 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
), ),
), ),
body: Container( body: Container(
height: MediaQuery.of(context).size.height - kToolbarHeight - MediaQuery.of(context).padding.top - MediaQuery.of(context).viewInsets.bottom,
child: Column( child: Column(
children: [ children: [
Expanded( Expanded(
child: SmartRefresher( child: chatDetailsList(),
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(),
),
flex: 1, flex: 1,
), ),
input(), input(),
@ -574,30 +582,68 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
/// ///
Widget chatDetailsList() { Widget chatDetailsList() {
return ListView.builder( return AnimatedList(
itemCount: messages.length, key: animatedListKey,
reverse: true, initialItemCount: messages.length,
padding: EdgeInsets.zero, controller: scrollController,
itemBuilder: (context, position) { physics: BouncingScrollPhysics()..frictionFactor(0.8),
return GestureDetector( itemBuilder: (context, position, animation) {
behavior: HitTestBehavior.opaque, return chatDetailsItem(position);
onTap: () {
setState(() {
if (emojiShowing) {
emojiShowing = !emojiShowing;
}
if (moreShow) {
moreShow = !moreShow;
}
});
FocusScope.of(context).requestFocus(FocusNode());
},
child: chatDetailsItem(position),
);
}, },
); );
} }
Future<double> 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) { Widget chatDetailsItem(position) {
bool isSelf = messages[position].fromId == selfUserId; bool isSelf = messages[position].fromId == selfUserId;
bool isText = messages[position].msgType == 1; bool isText = messages[position].msgType == 1;
@ -626,6 +672,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
style: TextStyle( style: TextStyle(
color: Color(0xFFA29E9E), color: Color(0xFFA29E9E),
fontSize: 10.sp, fontSize: 10.sp,
height: 1.0,
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
), ),
), ),
@ -662,6 +709,10 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
GestureDetector( GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () { onTap: () {
if (_toUser?.mid?.isEmpty ?? true) {
"用户信息错误".toast;
return;
}
Navigator.of(context).pushNamed( Navigator.of(context).pushNamed(
'/router/personal_page', '/router/personal_page',
arguments: { arguments: {
@ -673,8 +724,8 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
child: MImage( child: MImage(
_toUser?.avatar ?? '', _toUser?.avatar ?? '',
isCircle: true, isCircle: true,
height: 44.h, height: 44,
width: 44.h, width: 44,
fit: BoxFit.cover, fit: BoxFit.cover,
errorSrc: "assets/image/default_1.webp", errorSrc: "assets/image/default_1.webp",
fadeSrc: "assets/image/default_1.webp", fadeSrc: "assets/image/default_1.webp",
@ -705,7 +756,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
), ),
key: _buttonKey, key: _buttonKey,
padding: EdgeInsets.symmetric( padding: EdgeInsets.symmetric(
vertical: 8.h, vertical: 6,
horizontal: 12.w, horizontal: 12.w,
), ),
child: Text( child: Text(
@ -783,14 +834,14 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
), ),
key: _buttonKey, key: _buttonKey,
padding: EdgeInsets.symmetric( padding: EdgeInsets.symmetric(
vertical: 8.h, vertical: 6,
horizontal: 12.w, horizontal: 12.w,
), ),
child: Text( child: Text(
tex = messages[position].content, tex = messages[position].content,
textAlign: TextAlign.left, textAlign: TextAlign.left,
style: TextStyle( style: TextStyle(
height: 1.2.h, height: 1.2,
color: Colors.white, color: Colors.white,
fontSize: 17.sp, fontSize: 17.sp,
fontWeight: MyFontWeight.medium, fontWeight: MyFontWeight.medium,
@ -809,7 +860,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
Navigator.of(context).pushNamed( Navigator.of(context).pushNamed(
'/router/personal_page', '/router/personal_page',
arguments: { arguments: {
"memberId": "0", "memberId": selfUserId,
"inletType": 1, "inletType": 1,
}, },
); );
@ -817,8 +868,8 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
child: MImage( child: MImage(
userInfo?.headimg ?? "", userInfo?.headimg ?? "",
isCircle: true, isCircle: true,
height: 44.h, height: 44,
width: 44.h, width: 44,
fit: BoxFit.cover, fit: BoxFit.cover,
errorSrc: "assets/image/default_1.webp", errorSrc: "assets/image/default_1.webp",
fadeSrc: "assets/image/default_1.webp", fadeSrc: "assets/image/default_1.webp",
@ -831,7 +882,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
/// not self image /// not self image
if (!isSelf && isImage) if (!isSelf && isImage)
Padding( 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( child: Row(
children: [ children: [
MImage( MImage(
@ -851,19 +904,23 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
showMessageMenu(context, _buttonKey, messages[position]); showMessageMenu(context, _buttonKey, messages[position]);
}, },
onTap: () { onTap: () {
if (imageUrl.contains(messages[position].attach)) { if (imageUrl.contains(messages[position].attach) && (messages[position].attach?.isNotEmpty ?? false)) {
ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach)); ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach!));
} }
}, },
child: FutureBuilder( child: FutureBuilder(
future: fetchImageSize(messages[position]), future: fetchImageSize(messages[position]),
key: _buttonKey, key: _buttonKey,
builder: (BuildContext context, AsyncSnapshot snapshot) { builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == if (messages[position].attach?.isEmpty ?? true) {
ConnectionState.waiting || return SizedBox(
snapshot.hasError) { width: 180.w,
height: 200.h,
);
}
if (snapshot.connectionState == ConnectionState.waiting || snapshot.hasError) {
return Image.file( return Image.file(
File(messages[position].attach), File(messages[position].attach!),
width: 180.w, width: 180.w,
height: 200.h, height: 200.h,
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
@ -871,7 +928,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
); );
} else { } else {
return Image.file( return Image.file(
File(messages[position].attach), File(messages[position].attach!),
width: snapshot.data.width, width: snapshot.data.width,
height: snapshot.data.height, height: snapshot.data.height,
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
@ -892,7 +949,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
padding: EdgeInsets.only( padding: EdgeInsets.only(
left: 39.w, left: 39.w,
right: 17.w, right: 17.w,
top: 20.h, top: 10.h,
), ),
child: Row( child: Row(
children: [ children: [
@ -902,17 +959,23 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
showMessageMenu(context, _buttonKey, messages[position]); showMessageMenu(context, _buttonKey, messages[position]);
}, },
onTap: () { onTap: () {
if (imageUrl.contains(messages[position].attach)) { if (imageUrl.contains(messages[position].attach) && (messages[position].attach?.isNotEmpty ?? false)) {
ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach)); ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach!));
} }
}, },
child: FutureBuilder ( child: FutureBuilder (
future: fetchImageSize(messages[position]), future: fetchImageSize(messages[position]),
key: _buttonKey, key: _buttonKey,
builder: (BuildContext context, AsyncSnapshot snapshot) { 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) { if (snapshot.connectionState == ConnectionState.waiting || snapshot.hasError) {
return Image.file( return Image.file(
File(messages[position].attach), File(messages[position].attach!),
width: 180.w, width: 180.w,
height: 200.h, height: 200.h,
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
@ -920,7 +983,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
); );
} else { } else {
return Image.file( return Image.file(
File(messages[position].attach), File(messages[position].attach!),
width: snapshot.data.width, width: snapshot.data.width,
height: snapshot.data.height, height: snapshot.data.height,
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
@ -1038,11 +1101,10 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
GestureDetector( GestureDetector(
onTap: () async { onTap: () async {
await hxDatabase.deleteByMsgId("${message.id}"); await hxDatabase.deleteByMsgId("${message.id}");
int index = messages.indexOf(message);
messages.remove(message); messages.remove(message);
animatedListKey.currentState?.removeItem(index, (context, animation) {return Container();});
Navigator.pop(context); Navigator.pop(context);
if (mounted) {
setState(() {});
}
}, },
child: Column( child: Column(
children: [ children: [
@ -1083,26 +1145,28 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
} }
Future<Size> fetchImageSize(Message message) async { Future<Size> fetchImageSize(Message message) async {
String imageLocalPath = message.attach; String? imageLocalPath = message.attach;
String imageUrl = message.content; String imageUrl = message.content;
debugPrint("$imageLocalPath"); debugPrint("$imageLocalPath");
debugPrint("$imageUrl"); debugPrint("$imageUrl");
File file = File(imageLocalPath); if (imageLocalPath?.isEmpty ?? true) {
return Future.value(Size.zero);
}
File file = File(imageLocalPath!);
if (!(await file.exists())) { if (!(await file.exists())) {
await qiniu.downloadFile(imageUrl, savePath: imageLocalPath); await qiniu.downloadFile(imageUrl, savePath: imageLocalPath);
} }
Size size = Size.zero; Size size = Size.zero;
if (sharedPre != null) { String? sizeStr = SharedInstance.instance.getSize(imageLocalPath);
String? sizeStr = sharedPre!.getString(imageLocalPath); if (sizeStr != null && sizeStr != "") {
if (sizeStr != null && sizeStr != "") { Map<String, dynamic> sizeMap = jsonDecode(sizeStr);
Map<String, dynamic> sizeMap = jsonDecode(sizeStr); size = Size(sizeMap["width"], sizeMap["height"]);
size = Size(sizeMap["width"], sizeMap["height"]); if (size != Size.zero) {
if (size != Size.zero) { return size;
return size;
}
} }
} }
@ -1118,7 +1182,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
"width": size.width, "width": size.width,
"height": size.height, "height": size.height,
}; };
sharedPre?.setString(imageLocalPath, jsonEncode(sizeMap)); SharedInstance.instance.setSize(imageLocalPath, jsonEncode(sizeMap));
completer.complete(size); completer.complete(size);
})); }));
return completer.future; return completer.future;
@ -1141,7 +1205,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
Widget input() { Widget input() {
return Container( return Container(
color: Color(0xFFFDFCFC), 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( child: Column(
children: [ children: [
/// ///
@ -1171,11 +1237,11 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
if (commentText.trim() == "") { if (commentText.trim() == "") {
return; return;
} }
socketClient socketClient.sendMessage(_toUser?.mid ?? '', commentText)
.sendMessage(_toUser?.mid ?? '', commentText)
.then((value) { .then((value) {
Message message = value; Message message = value;
messages.insert(0, message); messages.add(message);
animatedListKey.currentState?.insertItem(messages.length - 1);
chatController.clear(); chatController.clear();
messageShowTime().then((value) { messageShowTime().then((value) {
refreshState(); refreshState();
@ -1203,14 +1269,13 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () { onTap: () {
_onSmileyTap(); _onSmileyTap();
jumpToBottom();
}, },
child: Container( child: Container(
padding: EdgeInsets.only(left: 15.w, right: 8.w), padding: EdgeInsets.only(left: 15.w, right: 8.w),
child: Image.asset( child: Image.asset(
"assets/image/icon_chat_emo.webp", "assets/image/icon_chat_emo.webp",
height: 26.h, height: 26,
width: 26.h, width: 26,
), ),
), ),
), ),
@ -1218,27 +1283,25 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () { onTap: () {
_onMoreTap(); _onMoreTap();
jumpToBottom();
}, },
child: Container( child: Container(
padding: EdgeInsets.only(left: 8.w, right: 19.w), padding: EdgeInsets.only(left: 8.w, right: 19.w),
child: Image.asset( child: Image.asset(
"assets/image/chat_more.webp", "assets/image/chat_more.webp",
height: 26.h, height: 26,
width: 26.h, width: 26,
), ),
), ),
), ),
], ],
), ),
SizedBox( SizedBox(
height: 16.h, height: 16,
), ),
/// ///
Offstage( if (emojiShowing)
offstage: !emojiShowing, Container(
child: SizedBox(
height: keyboard == -1 ? 270 : keyboard, height: keyboard == -1 ? 270 : keyboard,
width: MediaQuery.of(context).size.width, width: MediaQuery.of(context).size.width,
child: EmojiPicker( child: EmojiPicker(
@ -1246,12 +1309,12 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
config: Config( config: Config(
emojiViewConfig: EmojiViewConfig( emojiViewConfig: EmojiViewConfig(
columns: 7, columns: 7,
emojiSizeMax: 32 * (Platform.isIOS ? 1.10 : 1.0), emojiSizeMax: 28 * (Platform.isIOS ? 1.10 : 1.0),
verticalSpacing: 0, verticalSpacing: 0,
horizontalSpacing: 0, horizontalSpacing: 0,
backgroundColor: const Color(0xFFF2F2F2), backgroundColor: const Color(0xFFF2F2F2),
gridPadding: EdgeInsets.zero, gridPadding: EdgeInsets.zero,
recentsLimit: 28, recentsLimit: 35,
replaceEmojiOnLimitExceed: false, replaceEmojiOnLimitExceed: false,
noRecents: Text( noRecents: Text(
"最近使用", "最近使用",
@ -1274,17 +1337,22 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
categoryIcons: const CategoryIcons(), categoryIcons: const CategoryIcons(),
tabIndicatorAnimDuration: Duration(milliseconds: 0), tabIndicatorAnimDuration: Duration(milliseconds: 0),
), ),
bottomActionBarConfig: const BottomActionBarConfig(
backgroundColor: Colors.transparent,
buttonIconColor: Colors.blue,
showBackspaceButton: true,
showSearchViewButton: false,
),
swapCategoryAndBottomBar: false,
checkPlatformCompatibility: true, checkPlatformCompatibility: true,
), ),
), ),
), ),
),
/// ///
Offstage( if (moreShow)
offstage: !moreShow, Container(
child: Container( height: keyboard == -1 ? 167 : keyboard,
height: keyboard == -1 ? 167.h : keyboard,
child: Column( child: Column(
children: [ children: [
Container( Container(
@ -1383,7 +1451,6 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
], ],
), ),
), ),
),
], ],
), ),
); );
@ -1394,4 +1461,5 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
debugPrint(tex); debugPrint(tex);
Clipboard.setData(ClipboardData(text: tex)); Clipboard.setData(ClipboardData(text: tex));
} }
} }

18
lib/im/chat_friend_group.dart

@ -1,19 +1,15 @@
import 'dart:ui';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/base_data.dart';
import 'package:huixiang/data/social_info.dart'; import 'package:huixiang/data/social_info.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/retrofit_api.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/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/custom_underline_tabIndicator.dart';
import 'im_view/friend_groip_list.dart'; import 'im_view/friend_groip_list.dart';
@ -56,11 +52,13 @@ class _ChatFriendGroup extends State<ChatFriendGroup>
///(///) ///(///)
querySocialInfo() async { querySocialInfo() async {
SharedPreferences value = await SharedPreferences.getInstance();
apiService = ApiService(Dio(), apiService = ApiService(Dio(),
context: context, token: value.getString("token"), showLoading: false); context: context, token: SharedInstance.instance.token, showLoading: false,
);
BaseData<SocialInfo>? baseData = await apiService?.socialInfo().catchError((onError) {}); BaseData<SocialInfo>? baseData = await apiService?.socialInfo().catchError((onError) {
return BaseData<SocialInfo>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
infoNumber = baseData!.data; infoNumber = baseData!.data;

12
lib/im/chat_setting.dart

@ -1,13 +1,11 @@
import 'dart:ui';
import 'package:flutter/material.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:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/im/database/message.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:huixiang/view_widget/my_appbar.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../utils/font_weight.dart'; import '../../utils/font_weight.dart';
import '../main.dart'; import '../main.dart';
import '../data/im_user.dart'; import '../data/im_user.dart';
@ -34,11 +32,9 @@ class _ChatSetting extends State<ChatSetting> {
} }
void initData() async { void initData() async {
selfUserId = (await SharedPreferences.getInstance()).getString("userId") ?? ""; selfUserId = SharedInstance.instance.userId;
imUser = await hxDatabase.queryImUserById(widget.arguments?["userId"]); imUser = await hxDatabase.queryImUserById(widget.arguments?["userId"]);
setState(() { setState(() {});
});
} }
@override @override

277
lib/im/contact_share.dart

@ -1,14 +1,7 @@
import 'dart:ui';
import 'package:flutter/material.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: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:huixiang/view_widget/my_appbar.dart';
import 'package:flutter/cupertino.dart';
import '../../utils/font_weight.dart';
class ContactsShare extends StatefulWidget { class ContactsShare extends StatefulWidget {
final Map<String, dynamic>? arguments; final Map<String, dynamic>? arguments;
@ -22,7 +15,6 @@ class ContactsShare extends StatefulWidget {
} }
class _ContactsShare extends State<ContactsShare> { class _ContactsShare extends State<ContactsShare> {
ApiService? apiService;
final TextEditingController searchController = TextEditingController(); final TextEditingController searchController = TextEditingController();
int searchIndex = 0; int searchIndex = 0;
@ -43,92 +35,105 @@ class _ContactsShare extends State<ContactsShare> {
titleColor: Colors.black, titleColor: Colors.black,
), ),
body: Container( body: Container(
margin: EdgeInsets.only(top:14.h), margin: EdgeInsets.only(top: 14.h),
color: Colors.white, color: Colors.white,
child:SingleChildScrollView( child: SingleChildScrollView(
physics: BouncingScrollPhysics(), physics: BouncingScrollPhysics(),
child: GestureDetector( child: GestureDetector(
behavior: HitTestBehavior.translucent, behavior: HitTestBehavior.translucent,
onTap: () { onTap: () {
FocusScope.of(context).requestFocus(FocusNode()); FocusScope.of(context).requestFocus(FocusNode());
}, },
child:Column( child: Column(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
contactSearch(), contactSearch(),
Padding( Padding(
padding: EdgeInsets.only(left: 17.w,bottom:24.h), padding: EdgeInsets.only(
child: Text("最近联系(0)", left: 17.w, bottom: 24.h,
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: 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() { Widget contactSearch() {
return Container( return Container(
width: double.infinity, width: double.infinity,
margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 16.h), margin: EdgeInsets.only(
decoration: BoxDecoration( left: 16.w, right: 16.w, top: 4.h, bottom: 16.h,
borderRadius: BorderRadius.circular(6.w), ),
color: Color(0xFFF9FAF7), decoration: BoxDecoration(
), borderRadius: BorderRadius.circular(6.w),
child: Stack( color: Color(0xFFF9FAF7),
alignment: Alignment.center, ),
children: [ child: Stack(
Row( alignment: Alignment.center,
mainAxisAlignment: MainAxisAlignment.center, children: [
crossAxisAlignment: CrossAxisAlignment.center, Row(
children: [ mainAxisAlignment: MainAxisAlignment.center,
Image.asset( crossAxisAlignment: CrossAxisAlignment.center,
"assets/image/icon_search.webp", children: [
fit: BoxFit.fill, Image.asset(
), "assets/image/icon_search.webp",
SizedBox( fit: BoxFit.fill,
width: 4.w, ),
), SizedBox(
Text("搜索", width: 4.w,
style: TextStyle( ),
fontSize: 12.sp, Text("搜索",
color: Color(0xFFB3B3B3), style: TextStyle(
fontWeight: MyFontWeight.regular, 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,
), ),
) 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<ContactsShare> {
onTap: () {}, onTap: () {},
child: recentItem(), child: recentItem(),
); );
}); },
);
} }
Widget recentItem() { Widget recentItem() {
return Container( return Container(
margin: EdgeInsets.only(bottom: 14.h), margin: EdgeInsets.only(bottom: 14.h),
padding: EdgeInsets.only(left: 16.w,right: 14.w), padding: EdgeInsets.only(
child:Column( left: 16.w, right: 14.w,
children: [ ),
Row( child: Column(
children: [ children: [
// MImage( Row(
// "", children: [
// isCircle: true, Image.asset(
// width: 44, "assets/image/fuka_zj.webp",
// height: 44, height: 44,
// fit: BoxFit.cover, width: 44,
// errorSrc: "assets/image/default_1.webp", ),
// fadeSrc: "assets/image/default_1.webp", SizedBox(
// ), width: 10.w,
Image.asset( ),
"assets/image/fuka_zj.webp", Text("张五",
height:44, style: TextStyle(
width:44, 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<ContactsShare> {
onTap: () {}, onTap: () {},
child: recentItem(), child: recentItem(),
); );
}); },
);
} }
Widget mineFollowItem() { Widget mineFollowItem() {
return Container( return Container(
margin: EdgeInsets.only(bottom: 14.h), margin: EdgeInsets.only(bottom: 14.h),
padding: EdgeInsets.only(left: 16.w,right: 14.w), padding: EdgeInsets.only(
child:Column( left: 16.w, right: 14.w,
),
child: Column(
children: [ children: [
Row( Row(
children: [ 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( Image.asset(
"assets/image/fuka_zj.webp", "assets/image/fuka_zj.webp",
height:44, height: 44,
width:44, width: 44,
),
SizedBox(
width: 10.w,
), ),
SizedBox(width: 10.w,),
Text("小王", Text("小王",
style: TextStyle( style: TextStyle(
fontSize: 14.sp, fontSize: 14.sp,
color: Color(0xFF1A1A1A), color: Color(0xFF1A1A1A),
fontWeight: MyFontWeight.bold, fontWeight: MyFontWeight.bold,
)), ),
),
], ],
), ),
Container( Container(
height: 1.h, height: 1.h,
width: double.infinity, width: double.infinity,
color: Color(0xFFF7F7F7), color: Color(0xFFF7F7F7),
margin: EdgeInsets.only(left:54.w,top: 10.h), margin: EdgeInsets.only(
) left: 54.w, top: 10.h,
),
),
], ],
) ),
); );
} }
} }

4
lib/im/database/hx_database.dart

@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart';
import 'package:huixiang/constant.dart'; import 'package:huixiang/constant.dart';
import 'package:huixiang/im/database/message.dart'; import 'package:huixiang/im/database/message.dart';
import 'package:huixiang/im/database/migration.dart'; import 'package:huixiang/im/database/migration.dart';
import 'package:huixiang/utils/shared_preference.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart'; import 'package:sqflite/sqflite.dart';
@ -38,8 +39,7 @@ class HxDatabase {
_dbIsOpen() async { _dbIsOpen() async {
if (db == null || !db!.isOpen) { if (db == null || !db!.isOpen) {
var sp = await SharedPreferences.getInstance(); open(key: SharedInstance.instance.userId);
open(key: sp.getString("userId"));
} }
} }

4
lib/im/database/message.dart

@ -19,11 +19,11 @@ class Message {
String toId; String toId;
String replyId; String? replyId;
String content; String content;
String attach; String? attach;
int msgType; int msgType;

143
lib/im/im_search.dart

@ -2,7 +2,9 @@ import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.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/data/base_list_data.dart';
import 'package:huixiang/utils/shared_preference.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../data/im_user.dart'; import '../data/im_user.dart';
@ -33,9 +35,7 @@ class _ImSearch extends State<ImSearch> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) { selfUserId = SharedInstance.instance.userId;
selfUserId = value.getString("userId") ?? "";
});
} }
/// ///
@ -47,13 +47,10 @@ class _ImSearch extends State<ImSearch> {
/// ///
queryImSearch(keyword) async { queryImSearch(keyword) async {
if (apiService == null) { apiService ??= ApiService(Dio(),
SharedPreferences value = await SharedPreferences.getInstance(); context: context,
apiService = ApiService(Dio(), token: SharedInstance.instance.token,
context: context, showLoading: false);
token: value.getString("token"),
showLoading: false);
}
BaseListData<ImUser>? baseData = BaseListData<ImUser>? baseData =
await apiService?.memberSearch(keyword).catchError((onError) { await apiService?.memberSearch(keyword).catchError((onError) {
return BaseListData<ImUser>()..isSuccess = false; return BaseListData<ImUser>()..isSuccess = false;
@ -129,72 +126,78 @@ class _ImSearch extends State<ImSearch> {
) )
: Expanded( : Expanded(
child: Column( child: Column(
children: [ children: [
Padding( Padding(
padding: EdgeInsets.only(bottom: 19.h), padding: EdgeInsets.only(bottom: 19.h),
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (editingController.text != "" && if (editingController.text != "" &&
searchState == 1) searchState == 1)
Padding( Padding(
padding: EdgeInsets.only(left: 16.w), padding: EdgeInsets.only(left: 16.w),
child: Text( child: Text(
"搜索用户:", "搜索用户:",
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(
color: Color(0xFF060606), color: Color(0xFF060606),
fontSize: 16.sp, fontSize: 16.sp,
fontWeight: MyFontWeight.medium, fontWeight: MyFontWeight.medium,
),
), ),
), ),
), if (editingController.text != "" &&
if (editingController.text != "" && searchState == 1)
searchState == 1) Expanded(
Expanded( child: Text(
child: Text( editingController?.text ?? "",
editingController?.text ?? "", style: TextStyle(
style: TextStyle( fontSize: 16.sp,
fontSize: 16.sp, color: Color(0xFF32A060),
color: Color(0xFF32A060), fontWeight: MyFontWeight.regular),
fontWeight: MyFontWeight.regular), ))
)) ],
], ),
), ),
), if (editingController.text != "" && searchState == 1)
if (editingController.text != "" && searchState == 1) Expanded(
Expanded(
child: ListView.builder( child: ListView.builder(
itemCount: searchUser?.length ?? 0, itemCount: searchUser?.length ?? 0,
physics: BouncingScrollPhysics(), physics: BouncingScrollPhysics(),
shrinkWrap: true, shrinkWrap: true,
itemBuilder: (context, position) { itemBuilder: (context, position) {
return GestureDetector( return GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () { onTap: () {
setState(() { setState(() {
searchUserIndex = position; searchUserIndex = position;
});
Navigator.of(context).pushNamed(
'/router/personal_page',
arguments: {
"memberId": (searchUser[searchUserIndex]
.mid ??
"") ==
selfUserId
? "0"
: searchUser[searchUserIndex].mid,
"inletType": 0
}); });
FocusScope.of(context) String memberId = searchUser[searchUserIndex].mid ?? "";
.requestFocus(FocusNode()); 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]), ),
); )
}, ],
)) ),
], ),
)),
], ],
), ),
), ),

35
lib/im/im_view/friend_groip_list.dart

@ -1,15 +1,13 @@
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/data/base_data.dart'; import 'package:huixiang/data/base_data.dart';
import 'package:huixiang/data/follow.dart'; import 'package:huixiang/data/follow.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/data/im_user.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:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../retrofit/retrofit_api.dart'; import '../../retrofit/retrofit_api.dart';
import 'package:huixiang/im/database/message.dart'; import 'package:huixiang/im/database/message.dart';
@ -54,30 +52,12 @@ class _FriendGroupList extends State<FriendGroupList> {
super.dispose(); 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 { queryFollowList() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
apiService ??= ApiService( apiService ??= ApiService(
Dio(), Dio(),
context: context, context: context,
token: sharedPreferences.getString("token"), token: SharedInstance.instance.token,
showLoading: false, showLoading: false,
); );
@ -104,11 +84,10 @@ class _FriendGroupList extends State<FriendGroupList> {
/// ///
queryMutualFollowList() async { queryMutualFollowList() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
apiService ??= ApiService( apiService ??= ApiService(
Dio(), Dio(),
context: context, context: context,
token: sharedPreferences.getString("token"), token: SharedInstance.instance.token,
showLoading: false, showLoading: false,
); );
@ -163,7 +142,7 @@ class _FriendGroupList extends State<FriendGroupList> {
return GestureDetector( return GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () { onTap: () {
if (list![position].mid == sharedPreferences.getString("userId")) { if (list![position].mid == SharedInstance.instance.userId) {
SmartDialog.showToast("不能跟自己聊天", alignment: Alignment.center); SmartDialog.showToast("不能跟自己聊天", alignment: Alignment.center);
return; return;
} }
@ -171,9 +150,9 @@ class _FriendGroupList extends State<FriendGroupList> {
'/router/chat_details_page', '/router/chat_details_page',
arguments: { arguments: {
"toUser": ImUser( "toUser": ImUser(
avatar: list![position].avatar, avatar: list![position].avatar,
mid: list![position].mid, mid: list![position].mid,
nickname: list![position].nickname, nickname: list![position].nickname,
), ),
}, },
); );

377
lib/im/im_view/im_page.dart

@ -1,6 +1,7 @@
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.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:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/constant.dart'; import 'package:huixiang/constant.dart';
import 'package:huixiang/data/base_list_data.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/main.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/round_button.dart'; import 'package:huixiang/view_widget/round_button.dart';
@ -60,38 +62,31 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
@override @override
void dispose() { void dispose() {
super.dispose(); super.dispose();
OnChatMsgInstance.instance.onChatMessage = null; // OnChatMsgInstance.instance.onChatMessage = null;
socketClient.removeCallback(socketClient.userId); socketClient.removeCallback(socketClient.userId);
} }
@override @override
void initState() { void initState() {
super.initState(); super.initState();
OnChatMsgInstance.instance.onChatMessage = this; // OnChatMsgInstance.instance.onChatMessage = this;
initSocketClient(); initSocketClient();
SharedPreferences.getInstance().then((value) { apiService = ApiService(Dio(), token: SharedInstance.instance.token, context: context);
apiService = queryMsgStats();
ApiService(Dio(), token: value.getString("token"), context: context);
queryMsgStats();
});
} }
initSocketClient() async { initSocketClient() async {
SharedPreferences shared = await SharedPreferences.getInstance(); selfUserId = SharedInstance.instance.userId;
selfUserId = shared.getString("userId") ?? '';
socketClient.addCallback(selfUserId, (Message message) { socketClient.addCallback(selfUserId, (Message message) {
if (conversationIds.contains(message.conversationId)) { if (conversationIds.contains(message.conversationId)) {
conversationIds.remove(message.conversationId); conversationIds.remove(message.conversationId);
} }
conversationIds.insert(insertIndex, message.conversationId); conversationIds.insert(insertIndex, message.conversationId);
lastMessageMap[message.conversationId] = message; lastMessageMap[message.conversationId] = message;
listenerRefresh(message); listenerRefresh(message);
}); });
loadMessageList(); loadMessageList();
} }
@ -149,7 +144,7 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
/// update imuser info by mids /// update imuser info by mids
queryImUserInfo(userIds) async { queryImUserInfo(userIds) async {
List<ImUser> contacts = (await hxDatabase.queryImUser(userIds)) ?? []; List<ImUser> contacts = (await hxDatabase.queryImUser(userIds)) ?? [];
if (contacts?.isEmpty ?? true) { if (contacts.isEmpty) {
await queryMemberInfo(userIds); await queryMemberInfo(userIds);
return; return;
} else { } else {
@ -166,10 +161,11 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
.mGroupItem(); .mGroupItem();
List<String> topConversationIds = [], notTopUserIds = []; List<String> topConversationIds = [], notTopUserIds = [];
contactMap.forEach((key, value) { contactMap.forEach((key, value) {
if (value.isTop == 1) if (value.isTop == 1) {
topConversationIds.add(key); topConversationIds.add(key);
else } else {
notTopUserIds.add(key); notTopUserIds.add(key);
}
}); });
insertIndex = topConversationIds.length; insertIndex = topConversationIds.length;
this.conversationIds = topConversationIds..addAll(notTopUserIds); this.conversationIds = topConversationIds..addAll(notTopUserIds);
@ -178,8 +174,6 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
/// update one conversation last message ,and update conversation sort /// update one conversation last message ,and update conversation sort
void updateLastMessage(String conversationId) async { void updateLastMessage(String conversationId) async {
Message? message = await hxDatabase.lastMessage(conversationId); Message? message = await hxDatabase.lastMessage(conversationId);
debugPrint(
"lastmessage: $conversationId ${message?.content} ${message?.toJson()}");
if (message != null) { if (message != null) {
lastMessageMap[conversationId] = message; lastMessageMap[conversationId] = message;
await sortConversation(lastMessageMap); await sortConversation(lastMessageMap);
@ -205,10 +199,7 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
BaseListData<ImUser>? baseData = await apiService?.memberInfoByIds({ BaseListData<ImUser>? baseData = await apiService?.memberInfoByIds({
"mids": mids, "mids": mids,
}).catchError((error) { }).catchError((error) {
SmartDialog.showToast( return BaseListData<ImUser>()..isSuccess = false;
AppUtils.dioErrorTypeToString(error.type),
alignment: Alignment.center,
);
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
if (baseData!.data?.isNotEmpty ?? false) { if (baseData!.data?.isNotEmpty ?? false) {
@ -222,25 +213,17 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
}); });
refreshState(); refreshState();
} }
} else {
if (baseData?.msg?.isNotEmpty ?? false) {
SmartDialog.showToast(baseData?.msg ?? '', alignment: Alignment.center);
}
} }
} }
///App消息 ///App消息
queryMsgStats() async { queryMsgStats() async {
if (apiService == null) { apiService ??= ApiService(
SharedPreferences value = await SharedPreferences.getInstance(); Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString("token"), BaseListData<MsgStats>? baseData = await apiService?.stats().catchError((error) {
);
}
BaseListData<MsgStats>? baseData =
await apiService?.stats().catchError((error) {
return BaseListData<MsgStats>()..isSuccess = false; return BaseListData<MsgStats>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -304,9 +287,7 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
GestureDetector( GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTap: () { onTap: () {
Navigator.of(context) Navigator.of(context).pushNamed('/router/chat_friend_group').then((value) {
.pushNamed('/router/chat_friend_group')
.then((value) {
_refresh(); _refresh();
}); });
}, },
@ -337,9 +318,7 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
footer: CustomFooter( footer: CustomFooter(
loadStyle: LoadStyle.ShowWhenLoading, loadStyle: LoadStyle.ShowWhenLoading,
builder: (BuildContext context, LoadStatus? mode) { builder: (BuildContext context, LoadStatus? mode) {
return (messages.length == 0) return (messages.length == 0) ? Container() : MyFooter(mode);
? Container()
: MyFooter(mode);
}, },
), ),
controller: _refreshController, controller: _refreshController,
@ -367,7 +346,8 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
"assets/image/icon_system_message_new.webp", "assets/image/icon_system_message_new.webp",
S.of(context).xitongxiaoxi, S.of(context).xitongxiaoxi,
((msgNumber["2"] ?? 0) + (msgNumber["3"] ?? 0)) ((msgNumber["2"] ?? 0) + (msgNumber["3"] ?? 0))
.toString()), .toString(),
),
), ),
GestureDetector( GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
@ -434,7 +414,7 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
}); });
}, },
child: Container( 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), padding: EdgeInsets.symmetric(vertical: 10.h),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Color(0xFFFDFCFC), color: Color(0xFFFDFCFC),
@ -465,220 +445,153 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
); );
} }
bool _isDelEnter = false;
Map<String, ScrollController> idsController = {};
String? lastScrollId;
double lastScrollOffset = 0;
bool _isScrollOpen = false;
/// ///
Widget chatList() { Widget chatList() {
return ListView( return ListView(
padding: EdgeInsets.only(top: 8.h), padding: EdgeInsets.zero,
shrinkWrap: true, shrinkWrap: true,
physics: NeverScrollableScrollPhysics(), physics: NeverScrollableScrollPhysics(),
children: conversationIds.map((e) { 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); int position = conversationIds.indexOf(e);
return SingleChildScrollView( return InkWell(
physics: BouncingScrollPhysics(), onTap: () {
controller: scrollController, Navigator.of(context).pushNamed(
scrollDirection: Axis.horizontal, '/router/chat_details_page',
child: Row( arguments: {
children: [ "toUser": contactMap[conversationIds[position]],
GestureDetector( },
behavior: HitTestBehavior.opaque, ).then((value) {
onTap: () { unreadCountMap[conversationIds[position]] = 0;
Navigator.of(context).pushNamed( updateLastMessage(conversationIds[position]);
'/router/chat_details_page', _refresh();
arguments: { });
"toUser": contactMap[conversationIds[position]], },
}, child: chatItem(e),
).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;
});
},
),
],
),
); );
}).toList(), }).toList(),
); );
} }
Widget chatItem(conversationId) { Widget chatItem(conversationId) {
return Container( return Slidable(
padding: EdgeInsets.only( key: ValueKey(conversationId),
left: 16.w, direction: Axis.horizontal,
right: 17.w, closeOnScroll: true,
bottom: 18.h, endActionPane: ActionPane(
), dragDismissible: true,
width: MediaQuery.of(context).size.width, extentRatio: 0.25,
child: Row( motion: const ScrollMotion(),
children: [ children: [
MImage( SlidableAction(
!contactMap.containsKey(conversationId) onPressed: (BuildContext context) async {
? "" await hxDatabase.deleteByUser(conversationId);
: contactMap[conversationId]?.avatar ?? "", _refresh();
isCircle: true, },
height: 54.h, backgroundColor: Color(0xFFFE4A49),
width: 54.h, foregroundColor: Colors.white,
fit: BoxFit.cover, autoClose: true,
errorSrc: "assets/image/default_1.webp", label: S.of(context).shanchu,
fadeSrc: "assets/image/default_1.webp",
),
SizedBox(
width: 12.w,
), ),
Expanded( ],
child: Column( ),
crossAxisAlignment: CrossAxisAlignment.start, child: Container(
children: [ padding: EdgeInsets.only(
Row( left: 16.w,
children: [ right: 17.w,
Expanded( top: 8.h,
child: Text( bottom: 8.h,
!contactMap.containsKey(conversationId) ),
? "" width: MediaQuery.of(context).size.width,
: contactMap[conversationId]?.nickname ?? "", child: Row(
// overflow: TextOverflow.fade, children: [
maxLines: 1, MImage(
style: TextStyle( !contactMap.containsKey(conversationId) ? "" : contactMap[conversationId]?.avatar ?? "",
fontSize: 16.sp, isCircle: true,
color: Color(0xFF060606), height: 54,
fontWeight: MyFontWeight.semi_bold, 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(
Text( lastMessageMap[conversationId]?.time != null
lastMessageMap[conversationId]?.time != null ? AppUtils.timeFormatter(
? AppUtils.timeFormatter( DateTime.fromMillisecondsSinceEpoch(int.parse(
DateTime.fromMillisecondsSinceEpoch(int.parse( lastMessageMap[conversationId]?.time ?? "")))
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,
style: TextStyle( style: TextStyle(
fontSize: 12.sp, fontSize: 12.sp,
color: Color(0xFF353535), color: Color(0xFFA29E9E),
fontWeight: MyFontWeight.regular, fontWeight: MyFontWeight.regular,
), ),
), ),
), ],
if (unreadCountMap[conversationId] != null && ),
unreadCountMap[conversationId]! > 0) SizedBox(
Container( height: 7.h,
width: 16, ),
height: 16, Row(
decoration: BoxDecoration( children: [
borderRadius: BorderRadius.circular(100), Expanded(
color: Color(0xFFFF441A), child: Text(
), messageContent(lastMessageMap[conversationId]!),
child: RoundButton( maxLines: 1,
text: "${unreadCountMap[conversationId]}", overflow: TextOverflow.ellipsis,
textColor: Colors.white, style: TextStyle(
fontWeight: MyFontWeight.regular, fontSize: 12.sp,
backgroup: Color(0xFFFF441A), color: Color(0xFF353535),
fontSize: 10.sp, fontWeight: MyFontWeight.regular,
radius: 100, ),
), ),
), ),
], 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,
),
),
],
),
],
),
), ),
), ],
], ),
), ),
); );
} }

36
lib/im/im_view/on_chat_msg_instance.dart

@ -1,20 +1,20 @@
import 'on_chat_message.dart'; import 'on_chat_message.dart';
class OnChatMsgInstance{ // class OnChatMsgInstance{
factory OnChatMsgInstance() => _getInstance(); // factory OnChatMsgInstance() => _getInstance();
//
static OnChatMsgInstance get instance => _getInstance(); // static OnChatMsgInstance get instance => _getInstance();
//
static OnChatMsgInstance? _instance; // static OnChatMsgInstance? _instance;
//
OnChatMessage? onChatMessage; // OnChatMessage? onChatMessage;
//
OnChatMsgInstance._internal(); // OnChatMsgInstance._internal();
//
static OnChatMsgInstance _getInstance(){ // static OnChatMsgInstance _getInstance(){
if(_instance == null){ // if(_instance == null){
_instance = OnChatMsgInstance._internal(); // _instance = OnChatMsgInstance._internal();
} // }
return _instance!; // return _instance!;
} // }
} // }

131
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/data/user_info.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/my_tab.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:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../view_widget/no_data_view.dart';
class IntegralDetailedPage extends StatefulWidget { class IntegralDetailedPage extends StatefulWidget {
final arguments; final arguments;
@ -70,25 +71,28 @@ class _IntegralDetailedPage extends State<IntegralDetailedPage>
@override @override
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(Dio(),
apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
context: context, token: value.getString("token")), userInfo = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson));
userInfo = UserInfo.fromJson(jsonDecode(value.getString('user') ?? "")), queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_get",
queryDetail(widget.arguments["titleType"] == 1 ? "" : "bill_cate_point_get", widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_ADD" :""), widget.arguments["titleType"] == 1 ?"BILL_TYPE_BEAN_ADD" :"");
});
} }
queryDetail(category,type) async { queryDetail(category,type) async {
BaseData<PageInfo<UserBill>>? baseData = await apiService?.queryBillInfo({ BaseData<PageInfo<UserBill>>? baseData = await apiService?.queryBillInfo({
"current": current, "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", "order": "descending",
"size": 10, "size": 10,
"sort": "id" "sort": "id"
}).catchError((onError) { }).catchError((onError) {
refreshController.loadFailed(); refreshController.loadFailed();
refreshController.refreshFailed(); refreshController.refreshFailed();
return Future.value(null); return BaseData<PageInfo<UserBill>>()..isSuccess = false;
}); });
if (current == 1) userBill.clear(); if (current == 1) userBill.clear();
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -127,6 +131,7 @@ class _IntegralDetailedPage extends State<IntegralDetailedPage>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
return Scaffold( return Scaffold(
body: NestedScrollView( body: NestedScrollView(
headerSliverBuilder: (context, inner) { headerSliverBuilder: (context, inner) {
@ -181,14 +186,16 @@ class _IntegralDetailedPage extends State<IntegralDetailedPage>
style: TextStyle( style: TextStyle(
color: Colors.white, color: Colors.white,
fontWeight: MyFontWeight.medium, fontWeight: MyFontWeight.medium,
fontSize: 48.sp), fontSize: 48.sp,
),
), ),
Text( Text(
widget.arguments["titleType"] == 1 ? "我的印章" : S.of(context).wodejifenzhi, widget.arguments["titleType"] == 1 ? "我的印章" : S.of(context).wodejifenzhi,
style: TextStyle( style: TextStyle(
color: Color(0xFFF2F2F2), color: Color(0xFFF2F2F2),
fontSize: 12.sp, fontSize: 12.sp,
fontWeight: MyFontWeight.regular), fontWeight: MyFontWeight.regular,
),
), ),
], ],
), ),
@ -211,13 +218,18 @@ class _IntegralDetailedPage extends State<IntegralDetailedPage>
indicatorSize: TabBarIndicatorSize.label, indicatorSize: TabBarIndicatorSize.label,
labelColor: Colors.white, labelColor: Colors.white,
labelStyle: TextStyle( labelStyle: TextStyle(
fontSize: 16.sp, fontWeight: MyFontWeight.medium), fontSize: 16.sp,
fontWeight: MyFontWeight.medium,
),
unselectedLabelStyle: TextStyle( unselectedLabelStyle: TextStyle(
fontSize: 16.sp, fontWeight: MyFontWeight.medium), fontSize: 16.sp,
fontWeight: MyFontWeight.medium,
),
indicatorColor: Colors.white, indicatorColor: Colors.white,
unselectedLabelColor: Color(0xFFE6E6E6), unselectedLabelColor: Color(0xFFE6E6E6),
), ),
)), ),
),
), ),
]; ];
}, },
@ -238,13 +250,14 @@ class _IntegralDetailedPage extends State<IntegralDetailedPage>
onLoading: _loadMore, onLoading: _loadMore,
child: (userBill.length == 0) child: (userBill.length == 0)
? NoDataView( ? NoDataView(
src: "assets/image/xiao_fei.webp", src: "assets/image/xiao_fei.webp",
isShowBtn: false, isShowBtn: false,
text: "当前暂无记录哦~", text: "当前暂无记录哦~",
fontSize: 16.sp, fontSize: 16.sp,
margin: EdgeInsets.all(60.h), margin: EdgeInsets.all(60.h),
):ListView.builder( )
itemCount: userBill != null ? userBill.length : 0, : ListView.builder(
itemCount: userBill.length,
padding: EdgeInsets.only(top: 8, bottom: 8), padding: EdgeInsets.only(top: 8, bottom: 8),
itemBuilder: (context, position) { itemBuilder: (context, position) {
return Container( return Container(
@ -259,8 +272,9 @@ class _IntegralDetailedPage extends State<IntegralDetailedPage>
offset: Offset(0, 2), offset: Offset(0, 2),
blurRadius: 3, blurRadius: 3,
spreadRadius: 0, spreadRadius: 0,
) ),
]), ],
),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
@ -273,25 +287,29 @@ class _IntegralDetailedPage extends State<IntegralDetailedPage>
mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Padding(padding: EdgeInsets.only(bottom: 8.h), Padding(
padding: EdgeInsets.only(bottom: 8.h),
child: Text( child: Text(
userBill[position].type ?? "", userBill[position].type ?? "",
// S.of(context).qiandao, // S.of(context).qiandao,
style: TextStyle( style: TextStyle(
color: Colors.black, color: Colors.black,
fontSize: 14.sp, fontSize: 14.sp,
fontWeight: FontWeight.bold), fontWeight: FontWeight.bold,
),
),), ),),
Text( Text(
userBill[position].createTime ?? "", userBill[position].createTime ?? "",
style: TextStyle( style: TextStyle(
color: Color(0xFF4D4D4D), color: Color(0xFF4D4D4D),
fontSize: 12.sp, fontSize: 12.sp,
fontWeight: MyFontWeight.regular), fontWeight: MyFontWeight.regular,
) ),
),
], ],
), ),
)), ),
),
Container( Container(
margin: EdgeInsets.only(top: 2.h), margin: EdgeInsets.only(top: 2.h),
child: Text( child: Text(
@ -300,61 +318,12 @@ class _IntegralDetailedPage extends State<IntegralDetailedPage>
color: Color(0xFF4D4D4D), color: Color(0xFF4D4D4D),
fontSize: 14.sp, fontSize: 14.sp,
fontFamily: 'JDZhengHT', 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),
// ),
// )
// ],
// ),
); );
}, },
), ),

50
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/integral/intergra_view/integral_vip.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
@ -43,22 +44,17 @@ class _IntegralPage extends State<IntegralPage> {
final RefreshController refreshController = RefreshController(); final RefreshController refreshController = RefreshController();
querySignInfo() async { querySignInfo() async {
// SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai);
SharedPreferences value = await SharedPreferences.getInstance();
apiService = ApiService( apiService = ApiService(
Dio(), Dio(),
context: context, context: context,
token: value.getString("token"), token: SharedInstance.instance.token,
showLoading: false, showLoading: false,
); );
userInfo = UserInfo.fromJson(jsonDecode(value.getString("user") ?? "")); userInfo = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson));
BaseListData<Rank>? rankData = BaseListData<Rank>? rankData = await apiService?.rankList().catchError((onError) {
await apiService?.rankList().catchError((onError) {
SmartDialog.showToast(AppUtils.dioErrorTypeToString(onError.type),
alignment: Alignment.center);
refreshController.refreshFailed(); refreshController.refreshFailed();
return BaseListData<Rank>()..isSuccess = false;
}); });
if (rankData?.isSuccess ?? false) { if (rankData?.isSuccess ?? false) {
ranks.clear(); ranks.clear();
@ -69,13 +65,12 @@ class _IntegralPage extends State<IntegralPage> {
} }
if (ranks.length > 0) { if (ranks.length > 0) {
rankLevel = (ranks.indexWhere( rankLevel = (ranks.indexWhere((element) => element.id == userInfo?.memberRankVo?.id) + 1);
(element) => element.id == userInfo?.memberRankVo?.id) +
1);
} }
BaseData<SignInfo>? baseData = BaseData<SignInfo>? baseData = await apiService?.signInInfo().catchError((onError) {
await apiService?.signInInfo().catchError((onError) {}); return BaseData<SignInfo>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
signInfo = baseData!.data; signInfo = baseData!.data;
refreshController.refreshCompleted(); refreshController.refreshCompleted();
@ -89,20 +84,6 @@ class _IntegralPage extends State<IntegralPage> {
color: Colors.white, color: Colors.white,
child: Stack( child: Stack(
children: [ 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( Container(
decoration: BoxDecoration( decoration: BoxDecoration(
image: DecorationImage( image: DecorationImage(
@ -186,7 +167,8 @@ class _IntegralPage extends State<IntegralPage> {
0] ?? 0] ??
0) 0)
: 0) : 0)
.toString()), .toString(),
),
/// ///
InForPoints(signInfo, _signIn), InForPoints(signInfo, _signIn),
@ -215,13 +197,17 @@ class _IntegralPage extends State<IntegralPage> {
SmartDialog.showLoading( SmartDialog.showLoading(
msg: S.of(context).zhengzaijiazai, 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) { if (baseData?.isSuccess ?? false) {
setState(() {}); setState(() {});
SmartDialog.show( SmartDialog.show(
builder: (ctx) => SignInWidget( builder: (ctx) => SignInWidget(
"${(signInfo?.signInList?.length ?? 0) + 1}", "${(signInfo?.signInList?.length ?? 0) + 1}",
"${signInfo?.rewardList?[(signInfo?.signInList?.length ?? 0)]}")); "${signInfo?.rewardList?[(signInfo?.signInList?.length ?? 0)]}",
),
);
} else { } else {
SmartDialog.dismiss(); SmartDialog.dismiss();
} }

51
lib/integral/intergra_view/integral_vip.dart

@ -24,12 +24,13 @@ class IntegralVip extends StatefulWidget {
} }
class _IntegralVip extends State<IntegralVip> { class _IntegralVip extends State<IntegralVip> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(
padding: EdgeInsets.symmetric(vertical: 16.h,horizontal: 16.w), padding: EdgeInsets.symmetric(
vertical: 16.h,horizontal: 16.w,
),
child: Row( child: Row(
children: [ children: [
MImage( MImage(
@ -96,52 +97,6 @@ class _IntegralVip extends State<IntegralVip> {
], ],
), ),
), ),
// 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,
// // ),
// ],
// ),
// ],
// ),
// ),
], ],
), ),
); );

66
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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
@ -42,15 +43,12 @@ class _IntegralStoreDetailsPage extends State<IntegralStoreDetailsPage> {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) { apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = queryGoodsById();
ApiService(Dio(), context: context, token: value.getString("token")); if (SharedInstance.instance.userJson.isNotEmpty) {
queryGoodsById(); points = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)).points;
if (value.getString('user') != null) { happyBean = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)).happyBean;
points = UserInfo.fromJson(jsonDecode(value.getString('user')!)).points; }
happyBean = UserInfo.fromJson(jsonDecode(value.getString('user')!)).happyBean;
}
});
} }
Goods? goods; Goods? goods;
@ -58,7 +56,9 @@ class _IntegralStoreDetailsPage extends State<IntegralStoreDetailsPage> {
/// ///
queryGoodsById() async { queryGoodsById() async {
BaseData<Goods>? baseData = await apiService?.creditGoodsById(widget.arguments?["goodsId"] ?? "") BaseData<Goods>? baseData = await apiService?.creditGoodsById(widget.arguments?["goodsId"] ?? "")
.catchError((onError) {}); .catchError((onError) {
return BaseData<Goods>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
setState(() { setState(() {
goods = baseData?.data; goods = baseData?.data;
@ -77,7 +77,7 @@ class _IntegralStoreDetailsPage extends State<IntegralStoreDetailsPage> {
} }
refreshController.refreshCompleted(); refreshController.refreshCompleted();
}); });
}else { } else {
refreshController.refreshFailed(); refreshController.refreshFailed();
} }
} }
@ -175,9 +175,7 @@ class _IntegralStoreDetailsPage extends State<IntegralStoreDetailsPage> {
color: (payType > 0) color: (payType > 0)
? Color(0xFF32A060) ? Color(0xFF32A060)
: Color(0xFFD8D8D8), : Color(0xFFD8D8D8),
borderRadius: BorderRadius.circular( borderRadius: BorderRadius.circular(45),
45
),
), ),
alignment: Alignment.center, alignment: Alignment.center,
child: Text( child: Text(
@ -200,25 +198,27 @@ class _IntegralStoreDetailsPage extends State<IntegralStoreDetailsPage> {
//1-2-3- //1-2-3-
toExchangeOrder() async { toExchangeOrder() async {
await Navigator.of(context) await Navigator.of(context).pushNamed(
.pushNamed('/router/exchange_order_page', arguments: { '/router/exchange_order_page',
"goodsId": goods?.id, arguments: {
"name": goods?.name, "goodsId": goods?.id,
"money": goods?.money, "name": goods?.name,
"onePrice":goods?.onePrice, "money": goods?.money,
"oneMoney":goods?.oneMoney, "onePrice":goods?.onePrice,
"oneBean":goods?.oneBean, "oneMoney":goods?.oneMoney,
"price": goods?.price, "oneBean":goods?.oneBean,
"image": goods?.mainImgPath, "price": goods?.price,
"payType":payType, "image": goods?.mainImgPath,
"useTyped": (goods?.canPick ?? false) "payType":payType,
? 1 "useTyped": (goods?.canPick ?? false)
: (goods?.canDelivery ?? false) ? 1
? 2 : (goods?.canDelivery ?? false)
: 3, ? 2
}); : 3,
var shared = await SharedPreferences.getInstance(); },
points = UserInfo.fromJson(jsonDecode(shared.getString('user') ?? "")).points; );
points = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson)).points;
setState(() {}); setState(() {});
} }

4
lib/login/captcha/block_puzzle_captcha.dart

@ -151,7 +151,9 @@ class _BlockPuzzleCaptchaPageState extends State<BlockPuzzleCaptchaPage>
ApiService apiIpService = ApiService(Dio(), context: context); ApiService apiIpService = ApiService(Dio(), context: context);
CaptchaData baseData = await apiIpService.captchaGet({ CaptchaData baseData = await apiIpService.captchaGet({
"captchaType": "blockPuzzle", "captchaType": "blockPuzzle",
}).catchError((onError) {}); }).catchError((onError) {
return CaptchaData();
});
debugPrint("ClickWordCaptchaModel: ${baseData.toJson()}"); debugPrint("ClickWordCaptchaModel: ${baseData.toJson()}");

119
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/event_type.dart';
import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.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/border_text.dart';
import 'package:huixiang/view_widget/round_button.dart'; import 'package:huixiang/view_widget/round_button.dart';
import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view.dart';
@ -62,16 +63,10 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
String? areaCode; String? areaCode;
isLogin() async { isLogin() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (!SharedInstance.instance.isShowPrivacyPolicy) {
if (sharedPreferences.getBool("isShowPrivacyPolicy") == null ||
!(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) {
showAlertDialog(); showAlertDialog();
} }
if (SharedInstance.instance.token.isNotEmpty) {
if (sharedPreferences.containsKey('token') &&
sharedPreferences.getString("token") != null &&
sharedPreferences.getString("token") != "") {
Navigator.of(context).popAndPushNamed('/router/main_page'); Navigator.of(context).popAndPushNamed('/router/main_page');
} else { } else {
initController(); initController();
@ -133,8 +128,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
changeAlpha = (offset / (height - chaHeight) * (255)).toInt(); changeAlpha = (offset / (height - chaHeight) * (255)).toInt();
changeAlpha = (changeAlpha > 255 ? 255 : changeAlpha); changeAlpha = (changeAlpha > 255 ? 255 : changeAlpha);
changeAlpha = (changeAlpha < 0 ? 0 : changeAlpha); changeAlpha = (changeAlpha < 0 ? 0 : changeAlpha);
alpha = (initAlpha + offset / (height - chaHeight) * (255 - initAlpha)) alpha = (initAlpha + offset / (height - chaHeight) * (255 - initAlpha)).toInt();
.toInt();
alpha = (alpha > 255 ? 255 : alpha); alpha = (alpha > 255 ? 255 : alpha);
alpha = (alpha < 0 ? 0 : alpha); alpha = (alpha < 0 ? 0 : alpha);
}); });
@ -204,9 +198,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
Color statusInviteLineColor = Color(0xFF32A060); Color statusInviteLineColor = Color(0xFF32A060);
_sendCode() async { _sendCode() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (!SharedInstance.instance.isShowPrivacyPolicy) {
if (!sharedPreferences.containsKey("isShowPrivacyPolicy") ||
!(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) {
showAlertDialog(); showAlertDialog();
return; return;
} }
@ -223,10 +215,12 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
return; return;
} }
if (_sendCodeStatus == 0) { if (_sendCodeStatus == 0) {
client client?.sendVerify({
?.sendVerify( "areaCode": areaCode, "mobile": mobile, "verification": "",
{"areaCode": areaCode, "mobile": mobile, "verification": ""}) }).catchError((error) {
.then((value) => { SmartDialog.showToast("$error", alignment: Alignment.center);
return BaseData<dynamic>()..isSuccess = false;
}).then((value) => {
if (value.isSuccess ?? false) if (value.isSuccess ?? false)
{_sendCodeStatus = 1, countdown()} {_sendCodeStatus = 1, countdown()}
else else
@ -237,11 +231,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
alignment: Alignment.center), alignment: Alignment.center),
refresh() refresh()
} }
}) });
.catchError((error) {
SmartDialog.showToast("$error", alignment: Alignment.center);
return Future.value(null);
});
} }
} }
@ -279,9 +269,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
scrollToTop(); scrollToTop();
return; return;
} }
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (!SharedInstance.instance.isShowPrivacyPolicy) {
if (!sharedPreferences.containsKey("isShowPrivacyPolicy") ||
!(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) {
showAlertDialog(); showAlertDialog();
return; return;
} }
@ -327,12 +315,9 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
SmartDialog.showLoading( SmartDialog.showLoading(
msg: S.of(context).zhengzaijiazai, msg: S.of(context).zhengzaijiazai,
); );
BaseData<LoginInfo>? value = BaseData<LoginInfo>? value = await client?.memberLogin(param).catchError((error) {
await client?.memberLogin(param).catchError((error) {
print(error.message); print(error.message);
SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type), return BaseData<LoginInfo>()..isSuccess = false;
alignment: Alignment.center);
return Future.value(null);
}); });
// SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai); // SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai);
Future.delayed(Duration(seconds: 2), () { Future.delayed(Duration(seconds: 2), () {
@ -346,7 +331,8 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
"invite": invite, "invite": invite,
"interviewCouponList": value.data?.interviewCouponList, "interviewCouponList": value.data?.interviewCouponList,
"firstLoginCouponList": value.data?.firstLoginCouponList "firstLoginCouponList": value.data?.firstLoginCouponList
}); },
);
SmartDialog.dismiss(); SmartDialog.dismiss();
} else { } else {
SmartDialog.showToast("${value?.msg}", alignment: Alignment.center); SmartDialog.showToast("${value?.msg}", alignment: Alignment.center);
@ -356,13 +342,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
saveUserJson(userJson) { saveUserJson(userJson) {
var userEntity = UserEntity.fromJson(userJson); var userEntity = UserEntity.fromJson(userJson);
SharedPreferences.getInstance().then((value) => { SharedInstance.instance.saveUserInfo(userEntity);
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}"),
});
} }
late AnimationController animatedContainer; late AnimationController animatedContainer;
@ -402,8 +382,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
} }
animationStart() { animationStart() {
animatedContainer = animatedContainer = AnimationController(vsync: this, duration: Duration(seconds: 10));
AnimationController(vsync: this, duration: Duration(seconds: 10));
animation = AlignmentTween(begin: alignmentBegin, end: alignmentEnd) animation = AlignmentTween(begin: alignmentBegin, end: alignmentEnd)
.animate(animatedContainer); .animate(animatedContainer);
@ -458,8 +437,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
secondChild: uiPage(), secondChild: uiPage(),
firstCurve: Curves.easeInQuart, firstCurve: Curves.easeInQuart,
secondCurve: Curves.easeInQuart, secondCurve: Curves.easeInQuart,
crossFadeState: crossFadeState: isShowLogin ? CrossFadeState.showSecond : CrossFadeState.showFirst,
isShowLogin ? CrossFadeState.showSecond : CrossFadeState.showFirst,
duration: Duration(milliseconds: Platform.isIOS ? 1000 : 1000), duration: Duration(milliseconds: Platform.isIOS ? 1000 : 1000),
); );
} }
@ -1052,21 +1030,19 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
), ),
SizedBox( SizedBox(
height: 208.h, height: 208.h,
) ),
], ],
), ),
); );
} }
scrollToTop() { scrollToTop() {
RenderBox? renderBox = RenderBox? renderBox = loginKey.currentContext?.findRenderObject() as RenderBox?;
loginKey.currentContext?.findRenderObject() as RenderBox?;
var screenHeight = MediaQuery.of(context).size.height; var screenHeight = MediaQuery.of(context).size.height;
var scrollHeight = screenHeight * 1.47; var scrollHeight = screenHeight * 1.47;
var height = scrollHeight - (renderBox?.size.height ?? 0); var height = scrollHeight - (renderBox?.size.height ?? 0);
var chaHeight = screenHeight - (renderBox?.size.height ?? 0); var chaHeight = screenHeight - (renderBox?.size.height ?? 0);
scrollController?.animateTo(height - chaHeight, scrollController?.animateTo(height - chaHeight, duration: Duration(milliseconds: 500), curve: Curves.ease);
duration: Duration(milliseconds: 500), curve: Curves.ease);
} }
showAlertDialog() { showAlertDialog() {
@ -1108,29 +1084,30 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
), ),
), ),
Text.rich( Text.rich(
TextSpan(children: [ TextSpan(
TextSpan( children: [
text: S.of(context).yinsizhengce1, TextSpan(
style: TextStyle( text: S.of(context).yinsizhengce1,
fontWeight: MyFontWeight.medium, style: TextStyle(
fontSize: 14.sp,
height: 1.2.h,
color: Color(0xff727272),
),
),
TextSpan(
text: S.of(context).yinsixieyi,
style: TextStyle(
fontWeight: MyFontWeight.medium, fontWeight: MyFontWeight.medium,
fontSize: 14.sp, fontSize: 14.sp,
color: Color(0xff32A060)), height: 1.2.h,
recognizer: TapGestureRecognizer() color: Color(0xff727272),
..onTap = () { ),
Navigator.of(context) ),
.popAndPushNamed('/router/treaty_page'); 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( SizedBox(
height: 5.h, height: 5.h,
@ -1191,9 +1168,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
textColor: Colors.white, textColor: Colors.white,
fontSize: 12.sp, fontSize: 12.sp,
callback: () { callback: () {
SharedPreferences.getInstance().then((value) { SharedInstance.instance.showPrivacyPolicy();
value.setBool("isShowPrivacyPolicy", true);
});
SharesdkPlugin.uploadPrivacyPermissionStatus( SharesdkPlugin.uploadPrivacyPermissionStatus(
1, 1,
(success) => { (success) => {
@ -1217,7 +1192,7 @@ class _MyLoginPageState extends State<LoginPage> with TickerProviderStateMixin {
], ],
), ),
], ],
) ),
], ],
); );
}, },

80
lib/login/new_login_page.dart

@ -8,21 +8,23 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.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_data.dart';
import 'package:huixiang/data/channels.dart'; import 'package:huixiang/data/channels.dart';
import 'package:huixiang/data/examine_instance.dart'; import 'package:huixiang/data/examine_instance.dart';
import 'package:huixiang/data/user_entity.dart'; import 'package:huixiang/data/user_entity.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.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/border_text.dart';
import 'package:huixiang/view_widget/round_button.dart'; import 'package:huixiang/view_widget/round_button.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart'; import 'package:sharesdk_plugin/sharesdk_interface.dart';
import '../main.dart';
import 'captcha/block_puzzle_captcha.dart'; import 'captcha/block_puzzle_captcha.dart';
class NewLoginPage extends StatefulWidget { class NewLoginPage extends StatefulWidget {
@ -63,18 +65,12 @@ class _NewLoginPage extends State<NewLoginPage> {
} }
queryChannels() async { queryChannels() async {
BaseData<Channels>? baseData = BaseData<Channels>? baseData = await apiService?.appChannels().catchError((error) {
await apiService?.appChannels().catchError((error) {
print(error.message);
SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type),
alignment: Alignment.center);
return BaseData<Channels>()..isSuccess = false; return BaseData<Channels>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
channelsList = baseData!.data; channelsList = baseData!.data;
setState(() {}); setState(() {});
} else {
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center);
} }
} }
@ -121,9 +117,7 @@ class _NewLoginPage extends State<NewLoginPage> {
} }
_sendCode() async { _sendCode() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (!SharedInstance.instance.isShowPrivacyPolicy) {
if (!sharedPreferences.containsKey("isShowPrivacyPolicy") ||
!(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) {
showAlertDialog(); showAlertDialog();
return; return;
} }
@ -131,14 +125,18 @@ class _NewLoginPage extends State<NewLoginPage> {
if (mobile == "") { if (mobile == "") {
mobileStatus = 2; mobileStatus = 2;
mobileErrorText = S.of(context).qingshurushoujihao; mobileErrorText = S.of(context).qingshurushoujihao;
SmartDialog.showToast(S.of(context).qingshurushoujihao, SmartDialog.showToast(
alignment: Alignment.center); S.of(context).qingshurushoujihao,
alignment: Alignment.center,
);
setState(() {}); setState(() {});
return; return;
} }
if (!checkStatus) { if (!checkStatus) {
SmartDialog.showToast(S.of(context).gouxuanxieyi, SmartDialog.showToast(
alignment: Alignment.center); S.of(context).gouxuanxieyi,
alignment: Alignment.center,
);
return; return;
} }
if (_sendCodeStatus == 0) { if (_sendCodeStatus == 0) {
@ -171,15 +169,15 @@ class _NewLoginPage extends State<NewLoginPage> {
} }
_login() async { _login() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (!SharedInstance.instance.isShowPrivacyPolicy) {
if (!sharedPreferences.containsKey("isShowPrivacyPolicy") ||
!(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) {
showAlertDialog(); showAlertDialog();
return; return;
} }
if (!checkStatus) { if (!checkStatus) {
SmartDialog.showToast(S.of(context).gouxuanxieyi, SmartDialog.showToast(
alignment: Alignment.center); S.of(context).gouxuanxieyi,
alignment: Alignment.center,
);
return; return;
} }
var mobile = _controllerPhone.text; var mobile = _controllerPhone.text;
@ -189,12 +187,6 @@ class _NewLoginPage extends State<NewLoginPage> {
setState(() {}); setState(() {});
return; return;
} }
// if (mobile.length != 11) {
// mobileStatus = 2;
// mobileErrorText = S.of(context).phone_error;
// setState(() {});
// return;
// }
var code = _controllerCode.text; var code = _controllerCode.text;
if (code == "") { if (code == "") {
@ -221,16 +213,12 @@ class _NewLoginPage extends State<NewLoginPage> {
msg: S.of(context).zhengzaijiazai, msg: S.of(context).zhengzaijiazai,
); );
BaseData? value = await apiService?.memberLogin(param).catchError((error) { BaseData? value = await apiService?.memberLogin(param).catchError((error) {
print(error.message); return BaseData()..isSuccess = false;
SmartDialog.showToast(AppUtils.dioErrorTypeToString(error.type),
alignment: Alignment.center);
return Future.value(null);
}); });
// SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai); // SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai);
if (value?.isSuccess ?? false) { if (value?.isSuccess ?? false) {
var userInfo = value!.data; var userInfo = value!.data;
ExamineInstance.instance.isExamine = ExamineInstance.instance.isExamine = userInfo.authInfo?.account == "13800138000";
userInfo.authInfo?.account == "13800138000";
saveUserJson(userInfo.authInfo?.toJson()); saveUserJson(userInfo.authInfo?.toJson());
eventBus.fire(EventType(3)); eventBus.fire(EventType(3));
@ -249,28 +237,20 @@ class _NewLoginPage extends State<NewLoginPage> {
saveUserJson(userJson) { saveUserJson(userJson) {
var userEntity = UserEntity.fromJson(userJson); var userEntity = UserEntity.fromJson(userJson);
SharedPreferences.getInstance().then((value) => { SharedInstance.instance.saveUserInfo(userEntity);
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}"),
});
} }
isLogin() async { isLogin() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
if (sharedPreferences.getBool("isShowPrivacyPolicy") == null || if (!SharedInstance.instance.isShowPrivacyPolicy) {
!(sharedPreferences.getBool("isShowPrivacyPolicy") ?? false)) {
showAlertDialog(); showAlertDialog();
} }
if (sharedPreferences.containsKey('token') && if (SharedInstance.instance.token.isNotEmpty) {
sharedPreferences.getString("token") != null && ExamineInstance.instance.isExamine = SharedInstance.instance.mobile == "13800138000";
sharedPreferences.getString("token") != "") { WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
ExamineInstance.instance.isExamine = Navigator.of(context).popAndPushNamed('/router/main_page');
sharedPreferences.getString("mobile") == "13800138000"; });
Navigator.of(context).popAndPushNamed('/router/main_page');
} else { } else {
apiService = ApiService(Dio(), context: context); apiService = ApiService(Dio(), context: context);
initController(); initController();
@ -935,9 +915,7 @@ class _NewLoginPage extends State<NewLoginPage> {
textColor: Colors.white, textColor: Colors.white,
fontSize: 12.sp, fontSize: 12.sp,
callback: () { callback: () {
SharedPreferences.getInstance().then((value) { SharedInstance.instance.showPrivacyPolicy();
value.setBool("isShowPrivacyPolicy", true);
});
SharesdkPlugin.uploadPrivacyPermissionStatus( SharesdkPlugin.uploadPrivacyPermissionStatus(
1, 1,
(success) => { (success) => {

160
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/union/union_select_city.dart';
import 'package:huixiang/utils/ImgCachePath.dart'; import 'package:huixiang/utils/ImgCachePath.dart';
import 'package:huixiang/utils/qiniu.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/vip/user_vip_service_page.dart';
import 'package:huixiang/web/web_page.dart'; import 'package:huixiang/web/web_page.dart';
import 'package:huixiang/web/web_turntable_activity.dart'; import 'package:huixiang/web/web_turntable_activity.dart';
@ -141,7 +142,8 @@ import 'order/invoices_manage/invoices_title_info.dart';
void main() async { void main() async {
if (Platform.isAndroid) { if (Platform.isAndroid) {
SystemChrome.setSystemUIOverlayStyle( SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarColor: Colors.transparent)); SystemUiOverlayStyle(statusBarColor: Colors.transparent),
);
} }
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([ SystemChrome.setPreferredOrientations([
@ -157,24 +159,14 @@ void main() async {
locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH'); locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH');
} }
ImgCachePath(); ImgCachePath();
// initSdk();
bool isFirst = sharedPreferences.getBool("isFirst") ?? true; bool isFirst = sharedPreferences.getBool("isFirst") ?? true;
initShared(); SharedInstance.instance.init(sharedPreferences);
runApp(MyApp(locale, isFirst)); runApp(MyApp(locale, isFirst));
// FlutterBugly.postCatchedException((){
// });
// FlutterBugly.init(androidAppId: "204f207673",iOSAppId: "8bb92ba0f6");
} }
// final XgFlutterPlugin xgFlutterPlugin = XgFlutterPlugin();
late HxDatabase hxDatabase; late HxDatabase hxDatabase;
late SharedPreferences sharedPreferences;
initShared() async {
sharedPreferences = await SharedPreferences.getInstance();
}
initDatabase(String userId) async { initDatabase(String userId) async {
hxDatabase = HxDatabase(); hxDatabase = HxDatabase();
@ -199,87 +191,79 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ScreenUtilInit( return ScreenUtilInit(
builder: ( builder: (BuildContext context, Widget? child,) {
BuildContext context, return GetMaterialApp(
Widget? child, debugShowCheckedModeBanner: false,
) => title: Platform.isAndroid
GetMaterialApp( ? (ExamineInstance.instance.isExamine ? "海峡姐妹" : "")
debugShowCheckedModeBanner: false, : "",
title: Platform.isAndroid theme: ThemeData(
? (ExamineInstance.instance.isExamine ? "海峡姐妹" : "") primarySwatch: Colors.blue,
: "", // fontFamily: 'JDZhengHT',
theme: ThemeData( brightness: Brightness.light,
primarySwatch: Colors.blue, textTheme: TextTheme(
// fontFamily: 'JDZhengHT', labelMedium: TextStyle(fontSize: 16.sp),
textTheme: TextTheme( labelSmall: TextStyle(fontSize: 16.sp),
button: TextStyle(fontSize: 24.sp), labelLarge: TextStyle(fontSize: 16.sp),
bodyText1: TextStyle(fontSize: 12.sp), ),
bodyText2: TextStyle(fontSize: 16.sp),
), ),
), localeResolutionCallback: (locale, supportedLocales) {
localeResolutionCallback: (locale, supportedLocales) { print("locale: $locale");
print("locale: $locale"); print("supportedLocales: $supportedLocales");
print("supportedLocales: $supportedLocales"); return appLocale ?? locale;
return appLocale ?? locale; },
}, localizationsDelegates: [
localizationsDelegates: [ S.delegate,
S.delegate, GlobalMaterialLocalizations.delegate,
GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
GlobalCupertinoLocalizations.delegate, GlobalWidgetsLocalizations.delegate,
GlobalWidgetsLocalizations.delegate, ],
], localeListResolutionCallback: (List<Locale>? locales, Iterable<Locale> supportedLocales) {
localeListResolutionCallback: Locale? locale;
(List<Locale>? locales, Iterable<Locale> supportedLocales) { if (locales?.isNotEmpty ?? false) {
Locale? locale; print("locale: ${locales![0]}");
if (locales?.isNotEmpty ?? false) { if (locales[0].countryCode == "TW") {
print("locale: ${locales![0]}"); locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW');
if (locales[0].countryCode == "TW") { } else if (locales[0].countryCode == "US") {
locale = locale = Locale.fromSubtags(languageCode: 'en', countryCode: 'US');
Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW'); } else {
} else if (locales[0].countryCode == "US") { locale = Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH');
locale = }
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'); }
} else { return appLocale ?? locale ?? Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH');
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];
return appLocale ?? if (pageContentBuilder != null) {
locale ?? final Route route = CupertinoPageRoute(
Locale.fromSubtags(languageCode: 'zh', countryCode: 'CH'); builder: (context) {
}, return pageContentBuilder(context, arguments: settings.arguments);
supportedLocales: S.delegate.supportedLocales, },
home: (isFirst) ? GuidePage() : NewLoginPage(), settings: settings,
// home: StartPage(isFirst), );
builder: FlutterSmartDialog.init(), lastRoutePage = route;
onGenerateRoute: (settings) { return route;
final String? name = settings.name; }
if (lastRoutePage?.settings.name == name) { return MaterialPageRoute(
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(
builder: (context) { builder: (context) {
return pageContentBuilder(context, return NewLoginPage();
arguments: settings.arguments);
}, },
settings: settings, settings: settings,
); );
lastRoutePage = route; },
return route; );
} },
return MaterialPageRoute(
//
builder: (context) {
return NewLoginPage();
},
settings: settings,
);
},
),
); );
} }
} }

100
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/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/utils/native_event_handler.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:huixiang/view_widget/update_dialog.dart';
import 'package:package_info_plus/package_info_plus.dart'; import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.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_interface.dart';
import 'package:sharesdk_plugin/sharesdk_register.dart'; import 'package:sharesdk_plugin/sharesdk_register.dart';
import 'package:tpns_flutter_plugin/android/xg_android_api.dart'; import 'package:tpns_flutter_plugin/android/xg_android_api.dart';
@ -102,11 +102,9 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) { String userId = SharedInstance.instance.userId;
String userId = value.getString("userId") ?? ""; initDatabase(userId);
initDatabase(userId); connectSocket();
connectSocket();
});
pageController = PageController( pageController = PageController(
initialPage: initialPage:
@ -268,9 +266,7 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
MyNativeEventHandler( MyNativeEventHandler(
(String title, String message, String customContent, int type) { (String title, String message, String customContent, int type) {
print("xgPushClickAction2: $customContent"); print("xgPushClickAction2: $customContent");
SharedPreferences.getInstance().then((value) { SharedInstance.instance.savePushData(pushData: customContent);
value.setString("pushData", customContent);
});
}, },
), ),
); );
@ -291,16 +287,14 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
? (event["actionType"] == 0) ? (event["actionType"] == 0)
: (event["xg"]["msgtype"] == 1) && : (event["xg"]["msgtype"] == 1) &&
event[Platform.isAndroid ? "customMessage" : "custom"] != null) { event[Platform.isAndroid ? "customMessage" : "custom"] != null) {
SharedPreferences.getInstance().then((value) { SharedInstance.instance.savePushData(pushData: event[Platform.isAndroid ? "customMessage" : "custom"]);
value.setString("pushData",
event[Platform.isAndroid ? "customMessage" : "custom"]);
});
if ((ModalRoute.of(context)?.isActive ?? false) && if ((ModalRoute.of(context)?.isActive ?? false) &&
(ModalRoute.of(context)?.isCurrent ?? false)) { (ModalRoute.of(context)?.isCurrent ?? false)) {
pushRoute(); pushRoute();
} else { } else {
Navigator.of(context) Navigator.of(context).pushNamedAndRemoveUntil(
.pushNamedAndRemoveUntil('/router/main_page', (route) => false); '/router/main_page', (route) => false,
);
} }
} }
return event; return event;
@ -329,9 +323,7 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
} }
pushRoute() async { pushRoute() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (SharedInstance.instance.token.isEmpty) return;
if (sharedPreferences.getString("token") == null ||
sharedPreferences.getString("token") == "") return;
String? startIntent; String? startIntent;
if (Platform.isAndroid) startIntent = await Bridge.getStartIntent(); if (Platform.isAndroid) startIntent = await Bridge.getStartIntent();
print("intent:${startIntent ?? ''}"); print("intent:${startIntent ?? ''}");
@ -340,7 +332,7 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
pushData = startIntent; pushData = startIntent;
// pushData = """{"typed":1,"info":"1420304936817655808"}"""; // pushData = """{"typed":1,"info":"1420304936817655808"}""";
} else { } else {
pushData = sharedPreferences.getString("pushData") ?? ""; pushData = SharedInstance.instance.pushData;
} }
if (pushData == "") return; if (pushData == "") return;
Map<String, dynamic>? pushMap = jsonDecode(pushData); Map<String, dynamic>? pushMap = jsonDecode(pushData);
@ -401,7 +393,7 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
params["id"] = pushMap["info"]; params["id"] = pushMap["info"];
break; break;
} }
sharedPreferences.setString("pushData", ""); SharedInstance.instance.savePushData();
print("xgPushClickAction: routeName: $routeName"); print("xgPushClickAction: routeName: $routeName");
if (routeName != "") { if (routeName != "") {
Navigator.of(context).pushNamed(routeName, arguments: params); Navigator.of(context).pushNamed(routeName, arguments: params);
@ -410,25 +402,25 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
} }
queryUserInfo() async { queryUserInfo() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (SharedInstance.instance.token.isEmpty) return;
if (sharedPreferences.getString("token") == null || BaseData<UserInfo>? baseDate = await ApiService(
sharedPreferences.getString("token") == "") return;
BaseData<UserInfo> baseDate = await ApiService(
Dio(), Dio(),
context: context, context: context,
token: sharedPreferences.getString('token'), token: SharedInstance.instance.token,
).queryInfo().catchError((onError) {}); ).queryInfo().catchError((onError) {
sharedPreferences.setString('user', jsonEncode(baseDate.data)); return BaseData<UserInfo>()..isSuccess = false;
});
// if ((baseDate?.isSuccess ?? false) && baseDate?.data != null) {
String? mobile = baseDate.data?.phone; SharedInstance.instance.saveUser(baseDate!.data!);
if (mobile != null && mobile != "") { //
xgFlutterPlugin.setAccount(mobile, AccountType.PHONE_NUMBER); String? mobile = baseDate.data?.phone;
// xgFlutterPlugin.unbindWithIdentifier(identify: mobile, bindType: XGBindType.account) if (mobile != null && mobile != "") {
xgFlutterPlugin.bindWithIdentifier( xgFlutterPlugin.setAccount(mobile, AccountType.PHONE_NUMBER);
identify: mobile, xgFlutterPlugin.bindWithIdentifier(
bindType: XGBindType.account, identify: mobile,
); bindType: XGBindType.account,
);
}
} }
} }
@ -440,24 +432,23 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
///app自动更新 ///app自动更新
appAutoUpdate() async { appAutoUpdate() async {
SharedPreferences value = await SharedPreferences.getInstance(); apiService ??= ApiService(
if (apiService == null) { Dio(),
apiService = ApiService( context: context,
Dio(), token: SharedInstance.instance.token,
context: context, );
token: value.getString("token"),
);
}
PackageInfo packageInfo = await PackageInfo.fromPlatform(); PackageInfo packageInfo = await PackageInfo.fromPlatform();
BaseData<AppUpdate>? baseData = BaseData<AppUpdate>? baseData = await apiService?.appVersion().catchError((onError) {
await apiService?.appVersion().catchError((onError) {}); return BaseData<AppUpdate>()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
// baseData.data.appLastVersion = "2.0.17";
// baseData.data.appLastVersionUp = "1.0.1";
if (AppUtils.versionCompare( if (AppUtils.versionCompare(
packageInfo.version, "${baseData?.data?.appLastVersion}") && packageInfo.version,
AppUtils.versionCompare(value.getString("appLastVersion") ?? "1.0.0", "${baseData?.data?.appLastVersion}",
"${baseData?.data?.appLastVersion}")) { ) && AppUtils.versionCompare(
SharedInstance.instance.appLastVersion ?? "1.0.0",
"${baseData?.data?.appLastVersion}",
)) {
showDialog( showDialog(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
@ -475,7 +466,10 @@ class _MainPage extends State<MainPage> with WidgetsBindingObserver {
} }
} else { } else {
if (baseData?.msg?.isNotEmpty ?? false) { if (baseData?.msg?.isNotEmpty ?? false) {
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); SmartDialog.showToast(
"${baseData?.msg}",
alignment: Alignment.center,
);
} }
Navigator.of(context).pop(); Navigator.of(context).pop();
} }

8
lib/message/main_message_page.dart

@ -12,15 +12,13 @@ class MainMessagePage extends StatefulWidget {
} }
} }
class _MainMessagePage extends State<MainMessagePage> class _MainMessagePage extends State<MainMessagePage> with SingleTickerProviderStateMixin {
with SingleTickerProviderStateMixin {
var tabcontroller;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
if (tabcontroller == null)
tabcontroller = TabController(length: 2, vsync: this);
} }
@override @override

14
lib/message/real_time_info_page.dart

@ -17,7 +17,8 @@ class _RealTimeInfoPage extends State<RealTimeInfoPage> {
itemBuilder: (context, position) { itemBuilder: (context, position) {
return Container( return Container(
margin: EdgeInsets.only( 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), padding: EdgeInsets.only(top: 16, bottom: 16),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
@ -26,12 +27,17 @@ class _RealTimeInfoPage extends State<RealTimeInfoPage> {
color: Colors.black.withAlpha(12), color: Colors.black.withAlpha(12),
offset: Offset(0, 3), offset: Offset(0, 3),
blurRadius: 14, blurRadius: 14,
spreadRadius: 0) spreadRadius: 0,
),
], ],
borderRadius: BorderRadius.all(Radius.circular(8))), borderRadius: BorderRadius.all(
Radius.circular(8),
),
),
child: MessageItem(0), child: MessageItem(0),
); );
}), },
),
); );
} }
} }

27
lib/message/system_details.dart

@ -9,6 +9,7 @@ import 'package:huixiang/data/message.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
@ -50,11 +51,12 @@ class _SystemDetails extends State<SystemDetails> {
super.initState(); super.initState();
msgType = widget.arguments?["msgType"] ?? 0; msgType = widget.arguments?["msgType"] ?? 0;
SharedPreferences.getInstance().then((value) { apiService = ApiService(Dio(),
apiService = ApiService(Dio(), token: SharedInstance.instance.token,
token: value.getString("token"), showLoading: true, context: context); showLoading: true,
queryMessage(); context: context,
}); );
queryMessage();
} }
_refresh() { _refresh() {
@ -72,6 +74,7 @@ class _SystemDetails extends State<SystemDetails> {
}).catchError((onError) { }).catchError((onError) {
_refreshController.loadFailed(); _refreshController.loadFailed();
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return BaseData<PageInfo<Message>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
if (pageNum == 1) { if (pageNum == 1) {
@ -98,10 +101,10 @@ class _SystemDetails extends State<SystemDetails> {
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
// widget.refresh(); // widget.refresh();
queryMessage(); queryMessage();
SmartDialog.showToast(isFollow ? "取关成功" : "关注成功", SmartDialog.showToast(
alignment: Alignment.center); isFollow ? "取关成功" : "关注成功",
} else { alignment: Alignment.center,
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center); );
} }
} }
@ -120,14 +123,14 @@ class _SystemDetails extends State<SystemDetails> {
"parentId": messageRelational["additionId"].toString(), "parentId": messageRelational["additionId"].toString(),
"relationalId": messageRelational["businessId"].toString(), "relationalId": messageRelational["businessId"].toString(),
"relationalType": 4 "relationalType": 4
}).catchError((error) {}); }).catchError((error) {
return BaseData()..isSuccess = false;
});
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
commentTextController.text = ""; commentTextController.text = "";
FocusScope.of(context).unfocus(); FocusScope.of(context).unfocus();
Navigator.of(context).pop(); Navigator.of(context).pop();
SmartDialog.showToast("发布成功", alignment: Alignment.center); SmartDialog.showToast("发布成功", alignment: Alignment.center);
} else {
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center);
} }
} }

439
lib/message/system_message.dart

@ -10,6 +10,7 @@ import 'package:huixiang/data/page.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:huixiang/view_widget/no_data_view.dart';
@ -41,13 +42,10 @@ class _SystemMessagePage extends State<SystemMessagePage> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
apiService =
SharedPreferences.getInstance().then((value) { ApiService(Dio(), token: SharedInstance.instance.token, context: context);
apiService = queryMessage();
ApiService(Dio(), token: value.getString("token"), context: context); queryMsgStats();
queryMessage();
queryMsgStats();
});
} }
_refresh() { _refresh() {
@ -66,6 +64,7 @@ class _SystemMessagePage extends State<SystemMessagePage> {
}).catchError((onError) { }).catchError((onError) {
_refreshController.loadFailed(); _refreshController.loadFailed();
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return BaseData<PageInfo<Message>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -94,8 +93,7 @@ class _SystemMessagePage extends State<SystemMessagePage> {
} }
queryMsgStats() async { queryMsgStats() async {
BaseListData<MsgStats>? baseData = BaseListData<MsgStats>? baseData = await apiService?.stats().catchError((onError) {
await apiService?.stats().catchError((onError) {
return BaseListData<MsgStats>()..isSuccess = false; return BaseListData<MsgStats>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -120,35 +118,59 @@ class _SystemMessagePage extends State<SystemMessagePage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( 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, 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( body: SmartRefresher(
enablePullDown: true, enablePullDown: true,
enablePullUp: true, enablePullUp: true,
@ -167,136 +189,97 @@ class _SystemMessagePage extends State<SystemMessagePage> {
_refresh(); _refresh();
}); });
}, },
child: Container( child: SingleChildScrollView(
child: SingleChildScrollView( physics: BouncingScrollPhysics(),
physics: BouncingScrollPhysics(), child: Column(
child: Container( children: [
padding: EdgeInsets.only(bottom: 30.h), GestureDetector(
child: Column( behavior: HitTestBehavior.opaque,
children: [ onTap: () {
Container( Navigator.of(context).pushNamed(
color: Colors.white, '/router/system_details',
padding: EdgeInsets.only( arguments: {"msgType": 6},
top: MediaQuery.of(context).padding.top + 10.h, ).then((value) {
bottom: 15.h, setState(() {
right: 16.w), msgNumber["6"] = 0;
child: Row( });
mainAxisAlignment: MainAxisAlignment.spaceBetween, });
crossAxisAlignment: CrossAxisAlignment.center, },
children: [ child: messageItem("assets/image/icon_pl.webp", S.of(context).pinglun, msgNumber["6"].toString()),
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(),
],
), ),
), 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<SystemMessagePage> {
Widget messageItem(img, title, messageNum) { Widget messageItem(img, title, messageNum) {
return Container( return Container(
padding: EdgeInsets.only( padding: EdgeInsets.symmetric(
top: 14.h, horizontal: 14.w,
left: 14.w, vertical: 14,
bottom: 10.h,
right: 14.w,
), ),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
), ),
child: Column( child: Row(
children: [ children: [
Row( Image.asset(
children: [ img,
Image.asset( fit: BoxFit.fill,
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( child: RoundButton(
width: 12.w, text: messageNum,
textColor: Colors.white,
fontWeight: MyFontWeight.regular,
backgroup: Color(0xFFFF441A),
fontSize: 10.sp,
radius: 100,
), ),
Text( )
title, : Container(
style: TextStyle( padding: EdgeInsets.symmetric(
fontSize: 14.sp, horizontal: 4.w, vertical: 2.h,
color: Color(0xFF060606),
fontWeight: MyFontWeight.semi_bold,
),
), ),
SizedBox( decoration: BoxDecoration(
width: 9.w, borderRadius: BorderRadius.circular(100),
color: Color(0xFFFF441A),
), ),
if (messageNum != "0") child: RoundButton(
(((double.tryParse(messageNum) ?? 0) < 100) text: "99+",
? Container( textColor: Colors.white,
width: 16, fontWeight: MyFontWeight.regular,
height: 16, backgroup: Color(0xFFFF441A),
decoration: BoxDecoration( fontSize: 10.sp,
borderRadius: BorderRadius.circular(100), radius: 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,
), ),
], )),
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),
),
], ],
), ),
); );

26
lib/message/system_notice.dart

@ -6,6 +6,7 @@ import 'package:huixiang/data/message.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:huixiang/view_widget/no_data_view.dart';
@ -39,12 +40,8 @@ class _SystemNotice extends State<SystemNotice> {
void initState() { void initState() {
super.initState(); super.initState();
// msgType = widget.arguments["msgType"]; // msgType = widget.arguments["msgType"];
apiService = ApiService(Dio(), token: SharedInstance.instance.token, context: context);
SharedPreferences.getInstance().then((value) { queryMessage();
apiService =
ApiService(Dio(), token: value.getString("token"), context: context);
queryMessage();
});
} }
_refresh() { _refresh() {
@ -62,6 +59,7 @@ class _SystemNotice extends State<SystemNotice> {
}).catchError((onError) { }).catchError((onError) {
_refreshController.loadFailed(); _refreshController.loadFailed();
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return BaseData<PageInfo<Message>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -121,7 +119,8 @@ class _SystemNotice extends State<SystemNotice> {
padding: EdgeInsets.only( padding: EdgeInsets.only(
top: MediaQuery.of(context).padding.top + 10.h, top: MediaQuery.of(context).padding.top + 10.h,
bottom: 10.h, bottom: 10.h,
right: 16.w), right: 16.w,
),
child: Row( child: Row(
children: [ children: [
GestureDetector( GestureDetector(
@ -199,14 +198,18 @@ class _SystemNotice extends State<SystemNotice> {
}, },
child: buildMessageItem(messages[position]), child: buildMessageItem(messages[position]),
); );
}), },
),
], ],
)); ),
);
} }
Widget buildMessageItem(Message message) { Widget buildMessageItem(Message message) {
return Container( 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( child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@ -246,7 +249,8 @@ class _SystemNotice extends State<SystemNotice> {
fontWeight: MyFontWeight.semi_bold, fontWeight: MyFontWeight.semi_bold,
color: Color(0xFF060606), color: Color(0xFF060606),
), ),
)), ),
),
Text( Text(
message.updateTime ?? "", message.updateTime ?? "",
style: TextStyle( style: TextStyle(

10
lib/mine/coupon_page.dart

@ -6,6 +6,7 @@ import 'package:huixiang/data/coupon.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/coupon_details_dialog.dart'; import 'package:huixiang/view_widget/coupon_details_dialog.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
@ -43,12 +44,8 @@ class _CouponPage extends State<CouponPage> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
SharedPreferences.getInstance().then((value) { queryCard();
apiService =
ApiService(Dio(), context: context, token: value.getString('token'));
queryCard();
});
_refreshController = RefreshController(initialRefresh: false); _refreshController = RefreshController(initialRefresh: false);
} }
@ -74,6 +71,7 @@ class _CouponPage extends State<CouponPage> {
setState(() {}); setState(() {});
_refreshController.loadFailed(); _refreshController.loadFailed();
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return BaseData<PageInfo<Coupon>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
if (baseData?.data?.list?.isNotEmpty ?? false) { if (baseData?.data?.list?.isNotEmpty ?? false) {

7
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/coupon.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.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/classic_header.dart';
import 'package:huixiang/view_widget/coupon_details_dialog.dart'; import 'package:huixiang/view_widget/coupon_details_dialog.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
@ -38,10 +39,8 @@ class _CouponsPage extends State<CouponsPage> {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) { apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = ApiService(Dio(), context: context, token: value.getString('token')); queryCard();
queryCard();
});
_refreshController = RefreshController(initialRefresh: false); _refreshController = RefreshController(initialRefresh: false);
} }

20
lib/mine/fans_page.dart

@ -6,6 +6,7 @@ import 'package:huixiang/data/follow.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
@ -39,16 +40,13 @@ class _FansPage extends State<FansPage> with SingleTickerProviderStateMixin, Aut
super.initState(); super.initState();
_refreshController = RefreshController(); _refreshController = RefreshController();
SharedPreferences.getInstance().then((value) { apiService =
apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
ApiService(Dio(), context: context, token: value.getString("token")); _queryFollowList();
_queryFollowList();
});
} }
/// ///
_queryFollowList() async { _queryFollowList() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
BaseData<PageInfo<Follow>>? baseData = await apiService?.followList({ BaseData<PageInfo<Follow>>? baseData = await apiService?.followList({
"isMyFans": true, "isMyFans": true,
"pageNum": 1, "pageNum": 1,
@ -56,7 +54,7 @@ class _FansPage extends State<FansPage> with SingleTickerProviderStateMixin, Aut
}).catchError((error) { }).catchError((error) {
_refreshController.refreshFailed(); _refreshController.refreshFailed();
_refreshController.loadFailed(); _refreshController.loadFailed();
return Future.value(null); return BaseData<PageInfo<Follow>>()..isSuccess = false;
}); });
_refreshController.refreshCompleted(); _refreshController.refreshCompleted();
@ -68,7 +66,6 @@ class _FansPage extends State<FansPage> with SingleTickerProviderStateMixin, Aut
} }
list.addAll(baseData!.data!.list!); list.addAll(baseData!.data!.list!);
} }
print("list: ${list.length}");
if ((int.tryParse("${baseData?.data?.total}") ?? 0) < (pageNum * 10)) { if ((int.tryParse("${baseData?.data?.total}") ?? 0) < (pageNum * 10)) {
_refreshController.loadNoData(); _refreshController.loadNoData();
} }
@ -79,19 +76,18 @@ class _FansPage extends State<FansPage> with SingleTickerProviderStateMixin, Aut
/// ///
_vipFollow(followId,isFollow) async { _vipFollow(followId,isFollow) async {
BaseData? baseData = await apiService?.follow(followId).catchError((onError) { BaseData? baseData = await apiService?.follow(followId).catchError((onError) {
return Future.value(null); return BaseData()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
widget.refresh(); widget.refresh();
_queryFollowList(); _queryFollowList();
SmartDialog.showToast(isFollow?"取关成功":"关注成功", alignment: Alignment.center); SmartDialog.showToast(isFollow?"取关成功":"关注成功", alignment: Alignment.center);
} else {
SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center);
} }
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
return Scaffold( return Scaffold(
body: Container( body: Container(
margin: EdgeInsets.only(top: 2), margin: EdgeInsets.only(top: 2),
@ -128,7 +124,7 @@ class _FansPage extends State<FansPage> with SingleTickerProviderStateMixin, Aut
child: fansItem(list[position]), child: fansItem(list[position]),
); );
}, },
) ),
// NoDataView( // NoDataView(
// isShowBtn: false, // isShowBtn: false,
// text: "共关注0人", // text: "共关注0人",

14
lib/mine/follow_page.dart

@ -6,6 +6,7 @@ import 'package:huixiang/data/follow.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
@ -36,17 +37,13 @@ class _FollowPage extends State<FollowPage>
void initState() { void initState() {
super.initState(); super.initState();
_refreshController = RefreshController(); _refreshController = RefreshController();
apiService =
SharedPreferences.getInstance().then((value) { ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = _queryFollowList();
ApiService(Dio(), context: context, token: value.getString("token"));
_queryFollowList();
});
} }
/// ///
_queryFollowList() async { _queryFollowList() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
BaseData<PageInfo<Follow>>? baseData = await apiService?.followList({ BaseData<PageInfo<Follow>>? baseData = await apiService?.followList({
"isMyFans": false, "isMyFans": false,
"pageNum": 1, "pageNum": 1,
@ -54,7 +51,7 @@ class _FollowPage extends State<FollowPage>
}).catchError((error) { }).catchError((error) {
_refreshController.refreshFailed(); _refreshController.refreshFailed();
_refreshController.loadFailed(); _refreshController.loadFailed();
return Future.value(null); return BaseData<PageInfo<Follow>>()..isSuccess = false;
}); });
_refreshController.refreshCompleted(); _refreshController.refreshCompleted();
@ -88,6 +85,7 @@ class _FollowPage extends State<FollowPage>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
return Scaffold( return Scaffold(
body: Container( body: Container(
margin: EdgeInsets.only(top: 2), margin: EdgeInsets.only(top: 2),

27
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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.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:huixiang/view_widget/no_data_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -35,12 +36,9 @@ class _InvitationRecord extends State<InvitationRecord>
@override @override
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) { apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token, pay: true);
apiService = ApiService(Dio(), queryInviteMember();
context: context, token: value.getString("token"), pay: true); queryUserInfo();
queryInviteMember();
queryUserInfo();
});
} }
/// ///
@ -52,7 +50,7 @@ class _InvitationRecord extends State<InvitationRecord>
"pageSize": 100, "pageSize": 100,
}).catchError((error) { }).catchError((error) {
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return Future.value(null); return BaseData<PageInfo<Invitation>>() ..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
if (baseData?.data?.list?.isNotEmpty ?? false) { if (baseData?.data?.list?.isNotEmpty ?? false) {
@ -70,20 +68,15 @@ class _InvitationRecord extends State<InvitationRecord>
} }
queryUserInfo() async { queryUserInfo() async {
BaseData<UserInfo>? baseDate = BaseData<UserInfo>? baseDate = await apiService?.queryInfo().catchError((onError) {
await apiService?.queryInfo().catchError((onError) {
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return Future.value(null); return BaseData<UserInfo>()..isSuccess = false;
}); });
if (baseDate?.isSuccess ?? false) { if ((baseDate?.isSuccess ?? false) && baseDate!.data != null) {
setState(() { setState(() {
userInfo = baseDate!.data; userInfo = baseDate.data;
}); });
SharedPreferences.getInstance().then( SharedInstance.instance.saveUser(baseDate.data!);
(value) => {
value.setString('user', jsonEncode(baseDate!.data)),
},
);
_refreshController.refreshCompleted(); _refreshController.refreshCompleted();
} else { } else {
_refreshController.refreshFailed(); _refreshController.refreshFailed();

10
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/data/base_data.dart';
import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.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/border_text.dart';
import 'package:huixiang/view_widget/icon_text.dart'; import 'package:huixiang/view_widget/icon_text.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
@ -32,17 +33,14 @@ class _ManageAddressPage extends State<ManageAddressPage> {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = ApiService(Dio(), queryMemberAddress();
context: context, token: value.getString('token')),
queryMemberAddress(),
});
} }
List<Address>? addressList; List<Address>? addressList;
queryMemberAddress() async { queryMemberAddress() async {
BaseListData<Address>? baseData = await apiService?.queryMemberAddress().catchError((){ BaseListData<Address>? baseData = await apiService?.queryMemberAddress().catchError((error){
return BaseListData<Address>()..isSuccess = false; return BaseListData<Address>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {

10
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/coupon.dart';
import 'package:huixiang/data/page.dart'; import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.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/coupon_widget.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:pull_to_refresh/pull_to_refresh.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 'package:flutter_screenutil/flutter_screenutil.dart';
class MineCardInvalidPage extends StatefulWidget { class MineCardInvalidPage extends StatefulWidget {
@ -34,10 +34,8 @@ class _MineCardInvalidPage extends State<MineCardInvalidPage> {
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) => { apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = ApiService(Dio(), context: context, token: value.getString('token')), queryCard();
queryCard(),
});
_refreshController = RefreshController(initialRefresh: false); _refreshController = RefreshController(initialRefresh: false);
} }
@ -60,7 +58,7 @@ class _MineCardInvalidPage extends State<MineCardInvalidPage> {
}).catchError((error) { }).catchError((error) {
_refreshController.loadFailed(); _refreshController.loadFailed();
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return Future.value(null); return BaseData<PageInfo<Coupon>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
if (baseData?.data?.list?.isNotEmpty ?? false) { if (baseData?.data?.list?.isNotEmpty ?? false) {

14
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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
@ -35,12 +36,9 @@ class _MineGreenery extends State<MineGreenery> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
apiService = ApiService(Dio(),
SharedPreferences.getInstance().then((value) => { context: context, token: SharedInstance.instance.token);
apiService = ApiService(Dio(), pointGoodsList();
context: context, token: value.getString("token")),
pointGoodsList(),
});
} }
pointGoodsList() async { pointGoodsList() async {
@ -56,7 +54,7 @@ class _MineGreenery extends State<MineGreenery> {
await apiService?.creditGoods(param).catchError((onError) { await apiService?.creditGoods(param).catchError((onError) {
refreshController.loadFailed(); refreshController.loadFailed();
refreshController.refreshFailed(); refreshController.refreshFailed();
return Future.value(null); return BaseData<PageInfo<Goods>>()..isSuccess = false;
}); });
SmartDialog.dismiss(); SmartDialog.dismiss();
if (pageGoods?.isSuccess ?? false) { if (pageGoods?.isSuccess ?? false) {
@ -228,7 +226,7 @@ class _MineGreenery extends State<MineGreenery> {
children: [ children: [
Expanded( Expanded(
child: GridView.builder( child: GridView.builder(
itemCount: goods.length ?? 0, itemCount: goods.length,
padding: EdgeInsets.only( padding: EdgeInsets.only(
left: 16.w, left: 16.w,
right: 16.w, right: 16.w,

57
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/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/font_weight.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/classic_header.dart';
import 'package:huixiang/view_widget/login_tips_dialog.dart'; import 'package:huixiang/view_widget/login_tips_dialog.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:retrofit/error_logger.dart'; import 'package:retrofit/error_logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../data/banner.dart'; import '../data/banner.dart';
import '../data/coupon.dart'; import '../data/coupon.dart';
@ -54,18 +54,23 @@ class MinePageState extends State<MinePage> with AutomaticKeepAliveClientMixin,
List<BannerData> activityBannerData = []; List<BannerData> activityBannerData = [];
_toUserInfo() async { _toUserInfo() async {
SharedPreferences shared = await SharedPreferences.getInstance(); if (SharedInstance.instance.token.isEmpty) {
if (shared.getString("token") == null || shared.getString("token") == "") {
Navigator.of(context).pushReplacementNamed('/router/new_login_page', Navigator.of(context).pushReplacementNamed('/router/new_login_page',
arguments: {"login": "login"}); arguments: {"login": "login"});
return; return;
} }
(Platform.isAndroid && ExamineInstance.instance.isExamine) if (Platform.isAndroid && ExamineInstance.instance.isExamine) {
? await Navigator.of(context).pushNamed('/router/user_info_page') await Navigator.of(context).pushNamed('/router/user_info_page');
: await Navigator.of(context) } else {
.pushNamed('/router/personal_page', arguments: { if (SharedInstance.instance.userId.isNotEmpty) {
"memberId": "0", await Navigator.of(context).pushNamed(
}); '/router/personal_page',
arguments: {
"memberId": SharedInstance.instance.userId,
},
);
}
}
setState(() {}); setState(() {});
} }
@ -96,18 +101,11 @@ class MinePageState extends State<MinePage> with AutomaticKeepAliveClientMixin,
} }
queryUserInfo() async { queryUserInfo() async {
// SmartDialog.showLoading(msg: S.of(context).zhengzaijiazai); userInfo = UserInfo.fromJson(jsonDecode(SharedInstance.instance.userJson));
final SharedPreferences value = await SharedPreferences.getInstance();
if (value.containsKey('user') &&
value.getString('user') != null &&
value.getString('user') != "") {
userInfo = UserInfo.fromJson(jsonDecode(value.getString('user')!));
}
apiService = ApiService( apiService = ApiService(
Dio(), Dio(),
context: context, context: context,
token: value.getString('token'), token: SharedInstance.instance.token,
showLoading: false, showLoading: false,
errorLogger: this, errorLogger: this,
); );
@ -128,13 +126,9 @@ class MinePageState extends State<MinePage> with AutomaticKeepAliveClientMixin,
_refreshController.refreshFailed(); _refreshController.refreshFailed();
return BaseData<UserInfo>()..isSuccess = false; return BaseData<UserInfo>()..isSuccess = false;
}); });
if (baseDate?.isSuccess ?? false) { if ((baseDate?.isSuccess ?? false) && baseDate?.data != null) {
userInfo = baseDate?.data; userInfo = baseDate?.data;
SharedPreferences.getInstance().then( SharedInstance.instance.saveUser(baseDate!.data!);
(value) => {
value.setString('user', jsonEncode(baseDate?.data)),
},
);
_refreshController.refreshCompleted(); _refreshController.refreshCompleted();
} else { } else {
_refreshController.refreshFailed(); _refreshController.refreshFailed();
@ -144,11 +138,10 @@ class MinePageState extends State<MinePage> with AutomaticKeepAliveClientMixin,
///banner ///banner
queryActivityBanner() async { queryActivityBanner() async {
SharedPreferences value = await SharedPreferences.getInstance();
apiService = ApiService( apiService = ApiService(
Dio(), Dio(),
context: context, context: context,
token: value.getString("token"), token: SharedInstance.instance.token,
showLoading: false, showLoading: false,
errorLogger: this, errorLogger: this,
); );
@ -163,11 +156,10 @@ class MinePageState extends State<MinePage> with AutomaticKeepAliveClientMixin,
} }
queryCoupon() async { queryCoupon() async {
SharedPreferences value = await SharedPreferences.getInstance();
apiService = ApiService( apiService = ApiService(
Dio(), Dio(),
context: context, context: context,
token: value.getString("token"), token: SharedInstance.instance.token,
showLoading: false, showLoading: false,
errorLogger: this, errorLogger: this,
); );
@ -199,11 +191,10 @@ class MinePageState extends State<MinePage> with AutomaticKeepAliveClientMixin,
///(//) ///(//)
querySocialInfo() async { querySocialInfo() async {
SharedPreferences value = await SharedPreferences.getInstance();
apiService = ApiService( apiService = ApiService(
Dio(), Dio(),
context: context, context: context,
token: value.getString("token"), token: SharedInstance.instance.token,
showLoading: false, showLoading: false,
errorLogger: this, errorLogger: this,
); );
@ -222,8 +213,7 @@ class MinePageState extends State<MinePage> with AutomaticKeepAliveClientMixin,
/// ///
queryMsgStats() async { queryMsgStats() async {
BaseListData<MsgStats>? baseData = BaseListData<MsgStats>? baseData = await apiService?.stats().catchError((onError) {
await apiService?.stats().catchError((onError) {
return BaseListData<MsgStats>()..isSuccess = false; return BaseListData<MsgStats>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
@ -764,8 +754,7 @@ class MinePageState extends State<MinePage> with AutomaticKeepAliveClientMixin,
} }
toIntegralPage() async { toIntegralPage() async {
SharedPreferences shared = await SharedPreferences.getInstance(); if (SharedInstance.instance.token.isEmpty) {
if (shared.getString("token") == null || shared.getString("token") == "") {
LoginTipsDialog().show(context); LoginTipsDialog().show(context);
return; return;
} }

396
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/app_util.dart';
import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/utils/location.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/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
@ -38,7 +39,6 @@ class _MineShopDetails extends State<MineShopDetails> {
ApiService? apiService; ApiService? apiService;
int selectType = 0; int selectType = 0;
List<UserBill> userBill = []; List<UserBill> userBill = [];
int networkStatus = 0;
@override @override
void dispose() { void dispose() {
@ -51,11 +51,11 @@ class _MineShopDetails extends State<MineShopDetails> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
SharedPreferences.getInstance().then((value) { apiService = ApiService(Dio(),
apiService = token: SharedInstance.instance.token,
ApiService(Dio(), token: value.getString("token"), context: context); context: context,
vipDetail("", ""); );
}); vipDetail("", "");
startLocation(); startLocation();
} }
@ -65,28 +65,30 @@ class _MineShopDetails extends State<MineShopDetails> {
int current = 1; int current = 1;
vipDetail(latitude, longitude) async { vipDetail(latitude, longitude) async {
SharedPreferences value = await SharedPreferences.getInstance();
BaseData<VipCard>? baseData = await apiService?.vipDetail({ BaseData<VipCard>? baseData = await apiService?.vipDetail({
"id": widget.arguments["id"], "id": widget.arguments["id"],
"latitude": "$latitude", "latitude": "$latitude",
"longitude": "$longitude", "longitude": "$longitude",
}).catchError((onError) { }).catchError((onError) {
networkStatus = -1; return BaseData<VipCard>()..isSuccess = false;
return Future.value(null);
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
vipCard = baseData!.data; 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(); refreshController.loadComplete();
networkStatus = 1;
} else { } else {
refreshController.loadFailed(); refreshController.loadFailed();
} }
print("object:object");
setState(() {}); setState(() {});
} }
startLocation() async { startLocation() async {
// SmartDialog.showLoading(msg: S.current.zhengzaijiazai);
LocationInstance.getInstance().startLocation(context, (Position? result) { LocationInstance.getInstance().startLocation(context, (Position? result) {
if (result?.latitude != null && result?.longitude != null) { if (result?.latitude != null && result?.longitude != null) {
vipDetail(result?.latitude, result?.longitude); vipDetail(result?.latitude, result?.longitude);
@ -109,12 +111,11 @@ class _MineShopDetails extends State<MineShopDetails> {
"size": 10, "size": 10,
"sort": "id" "sort": "id"
}).catchError((onError) { }).catchError((onError) {
networkStatus == -1;
refreshController.refreshFailed(); refreshController.refreshFailed();
refreshController.loadFailed(); refreshController.loadFailed();
consumeRefreshController.refreshFailed(); consumeRefreshController.refreshFailed();
consumeRefreshController.loadFailed(); consumeRefreshController.loadFailed();
return Future.value(null); return BaseData<PageInfo<UserBill>>()..isSuccess = false;
}); });
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
if (current == 1) { if (current == 1) {
@ -133,7 +134,6 @@ class _MineShopDetails extends State<MineShopDetails> {
} else { } else {
current += 1; current += 1;
} }
networkStatus = 1;
} else { } else {
refreshController.refreshFailed(); refreshController.refreshFailed();
refreshController.loadFailed(); refreshController.loadFailed();
@ -153,138 +153,136 @@ class _MineShopDetails extends State<MineShopDetails> {
systemUiOverlayStyle: SystemUiOverlayStyle.dark, systemUiOverlayStyle: SystemUiOverlayStyle.dark,
leadingColor: Colors.black, leadingColor: Colors.black,
), ),
body: networkStatus == 0 body: Column(
? skeletonScreen() children: [
: Column( buildVipCard(),
Container(
margin: EdgeInsets.only(left: 14.w),
child: Row(
children: [ children: [
buildVipCard(), GestureDetector(
Container( onTap: () {
margin: EdgeInsets.only(left: 14.w), setState(() {
child: Row( selectType = 0;
});
},
child: Column(
children: [ children: [
GestureDetector( Text(
onTap: () { "适用门店",
setState(() { style: TextStyle(
selectType = 0; color:
}); Color(selectType == 0 ? 0xFF000000 : 0xFF868686),
}, fontSize: 15.sp,
child: Column( fontWeight: MyFontWeight.medium,
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),
)
],
), ),
), ),
SizedBox( SizedBox(
width: 20.w, height: 8.h,
), ),
// GestureDetector( if (selectType == 0)
// onTap: () { Container(
// setState(() { width: 52.w,
// selectType = 1; height: 2.h,
// billInfo(); color: Color(0xFF32A060),
// }); )
// },
// 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 SizedBox(
? Expanded( width: 20.w,
child: SmartRefresher( ),
controller: refreshController, // GestureDetector(
enablePullDown: false, // onTap: () {
enablePullUp: false, // setState(() {
footer: CustomFooter( // selectType = 1;
builder: (context, mode) { // billInfo();
return MyFooter(mode); // });
}, // },
), // child: Column(
physics: BouncingScrollPhysics(), // children: [
child: ListView.builder( // Text(
itemBuilder: (context, position) { // "余额明细",
return GestureDetector( // style: TextStyle(
onTap: () {}, // color:
child: shopItem(vipCard!.storeList![position]), // Color(selectType == 1 ? 0xFF000000 : 0xFF868686),
); // fontSize: 15.sp,
}, // fontWeight: MyFontWeight.medium,
padding: EdgeInsets.symmetric(vertical: 1), // ),
itemCount: vipCard?.storeList?.length ?? 0, // ),
), // SizedBox(
), // height: 8.h,
) // ),
: Expanded( // if (selectType == 1)
child: SmartRefresher( // Container(
controller: consumeRefreshController, // width: 52.w,
enablePullDown: true, // height: 2.h,
enablePullUp: true, // color: Color(0xFF32A060),
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,
),
),
),
], ],
), ),
),
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<MineShopDetails> {
topLeft: Radius.circular(6), topLeft: Radius.circular(6),
topRight: 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), padding: EdgeInsets.only(left: 12.w),
height: 62.h, height: 62.h,
@ -355,6 +361,14 @@ class _MineShopDetails extends State<MineShopDetails> {
topRight: Radius.circular(6), topRight: Radius.circular(6),
), ),
color: Colors.white, 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), padding: EdgeInsets.all(12.h),
child: Column( child: Column(
@ -823,58 +837,58 @@ class _MineShopDetails extends State<MineShopDetails> {
bool isRemake = true; bool isRemake = true;
// String totalPrice(orderInfo) { // String totalPrice(orderInfo) {
// if (orderInfo == null) return ""; // if (orderInfo == null) return "";
// double totalPrice = (double.tryParse(orderInfo.orderSum) + // double totalPrice = (double.tryParse(orderInfo.orderSum) +
// double.tryParse(orderInfo.postFee)); // double.tryParse(orderInfo.postFee));
// if (orderInfo.orderDetail != null && // if (orderInfo.orderDetail != null &&
// orderInfo.orderDetail.couponDTO != null) { // orderInfo.orderDetail.couponDTO != null) {
// totalPrice -= double.tryParse(orderInfo.orderDetail.couponDTO.money); // totalPrice -= double.tryParse(orderInfo.orderDetail.couponDTO.money);
// } // }
// return "$totalPrice"; // return "$totalPrice";
// } // }
// List<Widget> goodsItem(List<ProductsList> products) { // List<Widget> goodsItem(List<ProductsList> products) {
// if (products.length > 3) { // if (products.length > 3) {
// products = products.sublist(0, 3); // products = products.sublist(0, 3);
// } // }
// return products // return products
// .map( // .map(
// (e) => Container( // (e) => Container(
// margin: EdgeInsets.symmetric(horizontal: 2.w), // margin: EdgeInsets.symmetric(horizontal: 2.w),
// child: Column( // child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceAround, // mainAxisAlignment: MainAxisAlignment.spaceAround,
// crossAxisAlignment: CrossAxisAlignment.center, // crossAxisAlignment: CrossAxisAlignment.center,
// children: [ // children: [
// MImage( // MImage(
// e.skuImg, // e.skuImg,
// width: 75.w, // width: 75.w,
// height: 75.h, // height: 75.h,
// fit: BoxFit.contain, // fit: BoxFit.contain,
// errorSrc: "assets/image/default_1.webp", // errorSrc: "assets/image/default_1.webp",
// fadeSrc: "assets/image/default_1.webp", // fadeSrc: "assets/image/default_1.webp",
// ), // ),
// SizedBox( // SizedBox(
// height: 4.h, // height: 4.h,
// ), // ),
// if (isRemake) // if (isRemake)
// Container( // Container(
// width: 75.w, // width: 75.w,
// child: Text( // child: Text(
// e.productName, // e.productName,
// maxLines: 1, // maxLines: 1,
// textAlign: TextAlign.center, // textAlign: TextAlign.center,
// overflow: TextOverflow.ellipsis, // overflow: TextOverflow.ellipsis,
// style: TextStyle( // style: TextStyle(
// fontSize: 10.sp, // fontSize: 10.sp,
// fontWeight: MyFontWeight.regular, // fontWeight: MyFontWeight.regular,
// color: Color(0xFF353535), // color: Color(0xFF353535),
// ), // ),
// ), // ),
// ), // ),
// ], // ],
// ), // ),
// ), // ),
// ) // )
// .toList(); // .toList();
// } // }
} }

68
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:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.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/data/vip_card.dart';
import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/retrofit_api.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/font_weight.dart';
import 'package:huixiang/utils/shared_preference.dart';
import 'package:huixiang/view_widget/classic_header.dart'; import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart'; import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart'; import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/my_footer.dart'; import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/no_data_view.dart'; import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shimmer/shimmer.dart'; import 'package:shimmer/shimmer.dart';
class MineShopPage extends StatefulWidget { class MineShopPage extends StatefulWidget {
@ -42,11 +49,8 @@ class _MineShopPage extends State<MineShopPage> with WidgetsBindingObserver {
void initState() { void initState() {
super.initState(); super.initState();
refreshController = RefreshController(); refreshController = RefreshController();
SharedPreferences.getInstance().then((value) { apiService = ApiService(Dio(), context: context, token: SharedInstance.instance.token);
apiService = queryVipCard();
ApiService(Dio(), context: context, token: value.getString("token"));
queryVipCard();
});
_focusNode.addListener(() { _focusNode.addListener(() {
setState(() { setState(() {
hasFocus = _focusNode.hasFocus; hasFocus = _focusNode.hasFocus;
@ -97,6 +101,7 @@ class _MineShopPage extends State<MineShopPage> with WidgetsBindingObserver {
if (baseData?.isSuccess ?? false) { if (baseData?.isSuccess ?? false) {
coupons.clear(); coupons.clear();
coupons.addAll(baseData!.data ?? []); coupons.addAll(baseData!.data ?? []);
await loadShopColors();
refreshController.refreshCompleted(); refreshController.refreshCompleted();
networkStatus = 1; networkStatus = 1;
} else { } else {
@ -108,6 +113,19 @@ class _MineShopPage extends State<MineShopPage> 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return GestureDetector( return GestureDetector(
@ -129,7 +147,7 @@ class _MineShopPage extends State<MineShopPage> with WidgetsBindingObserver {
color: Colors.white, color: Colors.white,
padding: EdgeInsets.only( padding: EdgeInsets.only(
top: 10.h, top: 10.h,
bottom: 18.h, bottom: 18,
), ),
child: searchShop(), child: searchShop(),
), ),
@ -157,7 +175,7 @@ class _MineShopPage extends State<MineShopPage> with WidgetsBindingObserver {
) )
: ((coupons.length > 0) : ((coupons.length > 0)
? ListView.builder( ? ListView.builder(
padding: EdgeInsets.symmetric(vertical: 8.h), padding: EdgeInsets.symmetric(vertical: 8),
itemBuilder: (context, position) { itemBuilder: (context, position) {
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
@ -165,11 +183,10 @@ class _MineShopPage extends State<MineShopPage> with WidgetsBindingObserver {
'/router/mine_shop_recharge', '/router/mine_shop_recharge',
arguments: { arguments: {
"id": coupons[position].id, "id": coupons[position].id,
"tenantCode": "tenantCode": coupons[position].tenantCode,
coupons[position].tenantCode, "storeId": coupons[position].storeList?[0].id
"storeId": },
coupons[position].storeList?[0].id ).then((value) {
}).then((value) {
queryVipCard(showLoading: false); queryVipCard(showLoading: false);
}); });
}, },
@ -258,7 +275,6 @@ class _MineShopPage extends State<MineShopPage> with WidgetsBindingObserver {
Widget shopItem(VipCard vipCard) { Widget shopItem(VipCard vipCard) {
return Container( return Container(
width: double.infinity, width: double.infinity,
margin: EdgeInsets.only(bottom: 12.h, top: 14.h, left: 14.w, right: 14.w),
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@ -269,9 +285,18 @@ class _MineShopPage extends State<MineShopPage> with WidgetsBindingObserver {
topLeft: Radius.circular(6), topLeft: Radius.circular(6),
topRight: 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), padding: EdgeInsets.only(left: 12.w),
margin: EdgeInsets.only(top: 12, left: 14.w, right: 14.w),
height: 62.h, height: 62.h,
child: Row( child: Row(
children: [ children: [
@ -302,11 +327,22 @@ class _MineShopPage extends State<MineShopPage> with WidgetsBindingObserver {
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: new BorderRadius.only( borderRadius: new BorderRadius.only(
bottomRight: Radius.circular(6), bottomRight: Radius.circular(6),
topRight: Radius.circular(6), bottomLeft: Radius.circular(6),
), ),
color: Colors.white, color: Colors.white,
boxShadow: [
BoxShadow(
color: vipCard.color.withAlpha(10),
offset: Offset(0, 2),
blurRadius: 5,
spreadRadius: 1,
),
],
), ),
padding: EdgeInsets.all(12.h), padding: EdgeInsets.all(12.h),
margin: EdgeInsets.only(
bottom: 12, left: 14.w, right: 14.w,
),
child: Column( child: Column(
children: [ children: [
Row( Row(

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save