You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

665 lines
22 KiB

4 years ago
import 'dart:convert';
4 years ago
import 'dart:io';
4 years ago
import 'package:dio/dio.dart';
4 years ago
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
3 years ago
import 'package:flutter_easyloading/flutter_easyloading.dart';
3 years ago
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
3 years ago
import 'package:flutter_svg/flutter_svg.dart';
import 'package:huixiang/community/community_page.dart';
4 years ago
import 'package:huixiang/generated/l10n.dart';
3 years ago
import 'package:huixiang/home/home_page.dart';
4 years ago
import 'package:huixiang/main.dart';
4 years ago
import 'package:huixiang/mine/mine_page.dart';
3 years ago
import 'package:huixiang/retrofit/data/app_update.dart';
4 years ago
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/examine_instance.dart';
3 years ago
import 'package:huixiang/retrofit/data/user_info.dart';
4 years ago
import 'package:huixiang/retrofit/retrofit_api.dart';
4 years ago
import 'package:huixiang/union/union_page.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
3 years ago
import 'package:huixiang/utils/bridge.dart';
4 years ago
import 'package:huixiang/utils/event_type.dart';
3 years ago
import 'package:huixiang/utils/flutter_utils.dart';
3 years ago
import 'package:huixiang/utils/font_weight.dart';
3 years ago
import 'package:huixiang/utils/native_event_handler.dart';
3 years ago
import 'package:huixiang/view_widget/update_dialog.dart';
import 'package:huixiang/vip/vip_page.dart';
3 years ago
import 'package:package_info/package_info.dart';
4 years ago
import 'package:permission_handler/permission_handler.dart';
4 years ago
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_register.dart';
import 'package:tpns_flutter_plugin/android/xg_android_api.dart';
3 years ago
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
4 years ago
import 'community/order_page.dart';
4 years ago
class MainPage extends StatefulWidget {
final Map<String, dynamic> arguments;
MainPage({this.arguments});
4 years ago
@override
State<StatefulWidget> createState() {
return _MainPage();
}
}
3 years ago
class _MainPage extends State<MainPage> with WidgetsBindingObserver {
4 years ago
List<Widget> _widgetOptions;
4 years ago
4 years ago
List<String> icons;
3 years ago
final GlobalKey homePageKey = GlobalKey();
3 years ago
final GlobalKey minePageKey = GlobalKey();
3 years ago
final GlobalKey unionPageKey = GlobalKey();
final GlobalKey vipPageKey = GlobalKey();
3 years ago
// List<String> iconn;
3 years ago
ApiService apiService;
int lastTime = DateTime.now().millisecondsSinceEpoch;
String _platformVersion = 'Unknown';
4 years ago
3 years ago
@override
void dispose() {
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print("-didChangeAppLifecycleState-" + state.toString());
switch (state) {
case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
break;
case AppLifecycleState.resumed: //从后台切换前台,界面可见
pushRoute();
if (DateTime.now().millisecondsSinceEpoch - lastTime > 420000)
//处于后台**分钟后刷新应用
// Navigator.of(context).popAndPushNamed('/router/start_page');
setState((){});
3 years ago
break;
case AppLifecycleState.paused: // 界面不可见,后台
lastTime = DateTime.now().millisecondsSinceEpoch;
3 years ago
break;
case AppLifecycleState.detached: // APP结束时调用
break;
}
}
4 years ago
@override
void initState() {
super.initState();
pageController = PageController(
initialPage:
widget.arguments != null && widget.arguments["index"] != null
? widget.arguments["index"]
: 0);
if (widget.arguments != null && widget.arguments["index"] != null)
clickIndex = widget.arguments["index"];
3 years ago
WidgetsBinding.instance.addObserver(this);
3 years ago
EasyLoading.instance
..indicatorType = EasyLoadingIndicatorType.circle
3 years ago
// ..indicatorType = EasyLoadingIndicatorType.wave
// ..indicatorType = EasyLoadingIndicatorType.threeBounce
3 years ago
..loadingStyle = EasyLoadingStyle.dark
..indicatorSize = 35.0
..backgroundColor = Colors.white
..progressColor = Colors.green
..progressWidth = 3.0
..userInteractions = false
..dismissOnTap = false;
initSdk();
UmengCommonSdk.initCommon('6491509087568a379b5a1345', '6491509087568a379b5a1345', 'Umeng');
UmengCommonSdk.setPageCollectionModeManual();
initPlatformState();
4 years ago
pushRoute();
String invite = "";
var interviewCouponList;
var firstLoginCouponList;
if (widget.arguments != null &&
(widget.arguments["invite"] ?? "") != "" &&
widget.arguments["interviewCouponList"] != null) {
invite = widget.arguments["invite"];
interviewCouponList = widget.arguments["interviewCouponList"];
}
if (widget.arguments != null &&
widget.arguments["firstLoginCouponList"] != null) {
firstLoginCouponList = widget.arguments["firstLoginCouponList"];
}
4 years ago
_widgetOptions = <Widget>[
3 years ago
// BrandPage(),
HomePage(
homePageKey,
(index, jpIndex) {
if (index == 1) {
if (unionPageKey?.currentState != null) {
UnionPageState state = unionPageKey.currentState;
state.jumpIndex(jpIndex);
} else
_widgetOptions[1] = UnionPage(unionPageKey, jpIndex);
}
setState(() {
pageController.jumpToPage(index);
});
},
invite: invite,
interviewCouponList: interviewCouponList,
firstLoginCouponList: firstLoginCouponList,
),
3 years ago
// MainHomePage(),
UnionPage(unionPageKey, 0),
VipPage(vipPageKey),
Platform.isAndroid
? (ExamineInstance.instance.isExamine ? OrderPage() : CommunityPage())
: CommunityPage(),
// CommunityPage(),
3 years ago
MinePage(minePageKey),
4 years ago
];
icons = [
3 years ago
"assets/svg/jingbi.svg",
"assets/svg/lianmeng.svg",
"assets/svg/huixiang_vip.svg",
3 years ago
"assets/svg/shequn.svg",
"assets/svg/wode.svg",
4 years ago
];
3 years ago
// iconn = [
// "assets/image/icon_brand_n.webp",
// "assets/image/icon_bi_n.webp",
// "assets/image/icon_meng_n.webp",
// "assets/image/icon_wo_n.webp",
3 years ago
// ];
4 years ago
4 years ago
eventBus.on<EventType>().listen((event) {
4 years ago
if (event.type < 3) {
setState(() {});
}
4 years ago
});
queryUserInfo();
3 years ago
///App自动更新
3 years ago
appAutoUpdate();
}
3 years ago
final XgFlutterPlugin xgFlutterPlugin = XgFlutterPlugin();
Future<void> initPlatformState() async {
String platformVersion;
try {
platformVersion = (await UmengCommonSdk.platformVersion);
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
initSdk() async {
3 years ago
xgFlutterPlugin.stopXg();
///ios 调用startXg前需要调用此方法
xgFlutterPlugin.configureClusterDomainName("tpns.sh.tencent.com");
xgFlutterPlugin.setEnableDebug(true);
///此处配置为iOS的appID信息,Android信息在build.gradle文件中
xgFlutterPlugin.startXg("1680005688", "IYIB3R2XRE22");
if (Platform.isAndroid) {
XgAndroidApi androidApi = xgFlutterPlugin.getXgAndroidApi();
//小米
androidApi.setMiPushAppId(appId: "2882303761520050452");
androidApi.setMiPushAppKey(appKey: "5582005091452");
androidApi.enableOtherPush();
androidApi.regPush();
}
ShareSDKRegister shareSDKRegister = ShareSDKRegister();
shareSDKRegister.setupWechat(
"wx3b269e795ed23e5f",
"64020361b8ec4c99936c0e3999a9f249",
"https://hx.lotus-wallet.com/app/",
);
shareSDKRegister.setupFacebook(
"523308712059457",
"d3a1b6377100871799d8973fbe84794a",
"海峡姐妹",
);
SharesdkPlugin.regist(shareSDKRegister);
7 months ago
// LocationFlutterPlugin myLocPlugin = LocationFlutterPlugin();
// // 设置是否隐私政策
7 months ago
// myLocPlugin.setAgreePrivacy(true);
// BMFMapSDK.setAgreePrivacy(true);
// if (Platform.isIOS) {
// myLocPlugin.authAK("ylW2QPlsbERkho7jOgU4GQSeawmdUIoR");
// BMFMapSDK.setApiKeyAndCoordType(
// 'ylW2QPlsbERkho7jOgU4GQSeawmdUIoR',
// BMF_COORD_TYPE.BD09LL,
// );
// } else if (Platform.isAndroid) {
// BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);
// }
3 years ago
if (Platform.isAndroid) {
xgFlutterPlugin.getXgAndroidApi().addNativeEventHandler(
3 years ago
MyNativeEventHandler(
(String title, String message, String customContent, int type) {
3 years ago
print("xgPushClickAction2: $customContent");
SharedPreferences.getInstance().then((value) {
value.setString("pushData", customContent);
});
},
),
);
3 years ago
}
/// @typed: ARTICLE(1)文章 ACTIVITY(2)活动 SHOP(3)店铺 CREDIT_GOODS(4)积分商品 ORDER(5)订单 TREND(6)动态 MEMBER(7)用户 WALLET(8)平台余额/钱包 WELFARE(9)福利中心 COUPON(12)优惠券列表 CATE_BEAN(13)我的印章
xgFlutterPlugin.addEventHandler(xgPushClickAction: (event) async {
3 years ago
print("xgPushClickAction1: $event");
4 years ago
if (event["actionType"] == 2) return event;
3 years ago
if (Platform.isAndroid
? (event["actionType"] == 0)
: (event["xg"]["msgtype"] == 1) &&
event[Platform.isAndroid ? "customMessage" : "custom"] != null) {
4 years ago
SharedPreferences.getInstance().then((value) {
3 years ago
value.setString("pushData",
event[Platform.isAndroid ? "customMessage" : "custom"]);
4 years ago
});
3 years ago
if (ModalRoute.of(context).isActive &&
ModalRoute.of(context).isCurrent) {
3 years ago
pushRoute();
3 years ago
} else {
3 years ago
Navigator.of(context)
.pushNamedAndRemoveUntil('/router/main_page', (route) => false);
3 years ago
}
4 years ago
}
return event;
}, onReceiveNotificationResponse: (event) async {
try {
if (jsonDecode(event["customMessage"])["typed"] == 6) {
3 years ago
// HomePageState state = homePageKey.currentState;
// state.queryMsgStats();
MinePageState state = minePageKey.currentState;
3 years ago
state.queryMsgStats();
}
} catch (ex) {}
print("onReceiveNotificationResponse: ${event.toString()}");
return event;
}, onReceiveMessage: (event) async {
print("onReceiveMessage: ${event.toString()}");
return event;
3 years ago
}, onRegisteredDone: (event) async {
print("onRegisteredDone: ${event.toString()}");
return event;
}, xgPushDidBindWithIdentifier: (event) async {
print("xgPushDidBindWithIdentifier: ${event.toString()}");
return event;
3 years ago
});
4 years ago
}
4 years ago
pushRoute() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
3 years ago
if (sharedPreferences.getString("token") == null ||
sharedPreferences.getString("token") == "") return;
3 years ago
String startIntent;
if (Platform.isAndroid) startIntent = await Bridge.getStartIntent();
3 years ago
print("intent:$startIntent");
String pushData = "";
if (startIntent != null && startIntent != "") {
pushData = startIntent;
// pushData = """{"typed":1,"info":"1420304936817655808"}""";
} else {
pushData = sharedPreferences.getString("pushData");
}
4 years ago
if (pushData == null || pushData == "") return;
Map<String, dynamic> pushMap = jsonDecode(pushData);
if (pushMap != null) {
String routeName = "";
Map<String, dynamic> params = {};
switch (pushMap["typed"].toString()) {
case "1":
case "ARTICLE":
routeName = "/router/web_page";
4 years ago
params["articleId"] = pushMap["info"];
break;
case "2":
case "ACTIVITY":
routeName = "/router/web_page";
4 years ago
params["activityId"] = pushMap["info"];
break;
case "3":
case "SHOP":
routeName = "/router/store_order";
4 years ago
params["id"] = pushMap["info"];
params["tenant"] = pushMap["tenant"];
params["storeName"] = pushMap["storeName"];
4 years ago
break;
case "4":
case "CREDIT_GOODS":
4 years ago
routeName = "/router/integral_store_page";
params["goodsId"] = pushMap["info"];
break;
case "5":
case "ORDER":
3 years ago
routeName = "/router/order_details";
params["id"] = pushMap["info"];
break;
case "6":
case "MEMBER":
3 years ago
routeName = "/router/community_details";
params["businessId"] = pushMap["info"];
break;
case "8":
case "WALLET":
3 years ago
routeName = "/router/mine_wallet";
params["id"] = pushMap["info"];
break;
case "9":
case "WELFARE":
routeName = "/router/welfare_page";
params["id"] = pushMap["info"];
break;
case "12":
case "COUPON":
routeName = "/router/coupon_page";
params["id"] = pushMap["info"];
break;
case "13":
case "CATE_BEAN":
routeName = "/router/trading_card_page";
params["id"] = pushMap["info"];
break;
4 years ago
}
sharedPreferences.setString("pushData", "");
print("xgPushClickAction: routeName: $routeName");
if (routeName != "") {
Navigator.of(context).pushNamed(routeName, arguments: params);
}
}
}
4 years ago
queryUserInfo() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
3 years ago
if (sharedPreferences.getString("token") == null ||
sharedPreferences.getString("token") == "") return;
3 years ago
BaseData<UserInfo> baseDate = await ApiService(
Dio(),
context: context,
token: sharedPreferences.getString('token'),
).queryInfo().catchError((onError) {});
3 years ago
sharedPreferences.setString('user', jsonEncode(baseDate.data));
3 years ago
//用户登录时,注册推送的标识是手机号
3 years ago
String mobile = baseDate.data.phone;
if (mobile != null && mobile != "") {
3 years ago
xgFlutterPlugin.setAccount(mobile, AccountType.PHONE_NUMBER);
// xgFlutterPlugin.unbindWithIdentifier(identify: mobile, bindType: XGBindType.account)
3 years ago
xgFlutterPlugin.bindWithIdentifier(
7 months ago
identify: mobile,
bindType: XGBindType.account,
);
3 years ago
}
4 years ago
}
requestPermission() async {
4 years ago
if (!await Permission.storage.isGranted) {
4 years ago
await Permission.storage.request();
}
4 years ago
}
3 years ago
///app自动更新
appAutoUpdate() async {
3 years ago
SharedPreferences value = await SharedPreferences.getInstance();
3 years ago
if (apiService == null) {
apiService = ApiService(
Dio(),
context: context,
token: value.getString("token"),
3 years ago
);
}
3 years ago
PackageInfo packageInfo = await PackageInfo.fromPlatform();
BaseData<AppUpdate> baseData =
await apiService.appVersion().catchError((onError) {});
3 years ago
if (baseData != null && baseData.isSuccess) {
// baseData.data.appLastVersion = "2.0.17";
3 years ago
// baseData.data.appLastVersionUp = "1.0.1";
if (AppUtils.versionCompare(
packageInfo.version, baseData.data?.appLastVersion) &&
AppUtils.versionCompare(value.getString("appLastVersion") ?? "1.0.0",
baseData.data?.appLastVersion)) {
3 years ago
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return WillPopScope(
child: UpdateDialog(packageInfo.version, baseData.data),
3 years ago
onWillPop: () async {
return Future.value(false);
});
},
);
} else {
3 years ago
return;
}
} else {
SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
3 years ago
Navigator.of(context).pop();
}
}
PageController pageController;
4 years ago
4 years ago
@override
Widget build(BuildContext context) {
return Scaffold(
4 years ago
resizeToAvoidBottomInset: false,
4 years ago
body: Container(
child: PageView(
controller: pageController,
children: _widgetOptions,
physics: NeverScrollableScrollPhysics(),
onPageChanged: (index) {
clickIndex = index;
setState(() {});
},
),
4 years ago
),
extendBody: true,
bottomNavigationBar: Container(
alignment: Platform.isAndroid ? Alignment.center : Alignment.topCenter,
decoration: BoxDecoration(
4 years ago
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(12),
offset: Offset(0, 2),
blurRadius: 4,
spreadRadius: 0,
7 months ago
),
4 years ago
],
3 years ago
borderRadius: BorderRadius.vertical(
top: Radius.circular(4),
4 years ago
),
),
4 years ago
height: 82.h,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
3 years ago
// bottomNavigationBigItem(S.of(context).pinpai, 0),
bottomNavigationItem(S.of(context).main_menu1, 0),
bottomNavigationItem(S.of(context).main_menu2, 1),
// bottomNavigationItem(S.of(context).main_menu3 , 2),
bottomNavigationItem(S.of(context).main_menu5, 2),
bottomNavigationItem(
Platform.isAndroid
? (ExamineInstance.instance.isExamine
? "订单"
: S.of(context).main_menu3)
: S.of(context).main_menu3,
3),
bottomNavigationItem(S.of(context).main_menu4, 4),
4 years ago
],
),
),
);
}
3 years ago
var clickIndex = 0;
4 years ago
4 years ago
Widget bottomNavigationItem(text, index) {
4 years ago
var isSelected = index == clickIndex;
return Expanded(
child: InkWell(
onTap: () {
setState(() {
clickIndex = index;
4 years ago
// if (index == 1) {
// debugDumpApp();
// }
4 years ago
pageController.jumpToPage(clickIndex);
4 years ago
});
},
child: Container(
width: 45.w,
child: Column(
4 years ago
mainAxisAlignment: Platform.isAndroid
? MainAxisAlignment.center
: MainAxisAlignment.start,
4 years ago
crossAxisAlignment: CrossAxisAlignment.center,
children: [
4 years ago
if (Platform.isIOS)
4 years ago
SizedBox(
height: 4.h,
),
3 years ago
// AnimatedCrossFade(
// firstChild: SvgPicture.asset(
// icons[index],
// width: 30,
// height: 30,
// fit: BoxFit.contain,
// ),
// // Image.asset(
// // icons[index],
// // width: 30,
// // height: 30,
// // fit: BoxFit.contain,
// // ),
// secondChild: Image.asset(
// iconn[index],
// width: 30,
// height: 30,
// fit: BoxFit.contain,
// ),
// crossFadeState: isSelected
// ? CrossFadeState.showFirst
// : CrossFadeState.showSecond,
// duration: Duration(milliseconds: 200),
// ),
SvgPicture.asset(
icons[index],
width: 30,
height: 30,
color: isSelected ? Color(0xFF32A060) : Color(0xFFE6E6E6),
fit: BoxFit.contain,
4 years ago
),
Text(
4 years ago
text,
4 years ago
style: TextStyle(
3 years ago
fontSize: 10,
3 years ago
fontWeight: MyFontWeight.semi_bold,
3 years ago
color: Color(isSelected ? 0xFF32A060 : 0xFFC6C6C6),
3 years ago
),
4 years ago
),
],
),
),
),
flex: 1,
);
}
// Widget bottomNavigationBigItem(text, index) {
// var isSelected = index == clickIndex;
// return Expanded(
// child: InkWell(
// onTap: () {
// setState(() {
// clickIndex = index;
// pageController.jumpToPage(clickIndex);
// });
// },
// child: Container(
// width: 45.w,
// alignment: Alignment.center,
// child: AnimatedCrossFade(
// firstCurve: Curves.easeIn,
// secondCurve: Curves.ease,
// sizeCurve: Curves.easeInOut,
// duration: Duration(milliseconds: 50),
// firstChild: Container(
// padding: EdgeInsets.all(4),
// height: 82.h,
// alignment:
// Platform.isAndroid ? Alignment.center : Alignment.topCenter,
// child: Image.asset(
// icons[index],
// width: 45,
// height: 45,
// fit: BoxFit.contain,
// ),
// ),
// secondChild: Column(
// mainAxisAlignment: Platform.isAndroid
// ? MainAxisAlignment.center
// : MainAxisAlignment.start,
// crossAxisAlignment: CrossAxisAlignment.center,
// children: [
// if (Platform.isIOS)
// SizedBox(
// height: 4.h,
// ),
// Image.asset(
// iconn[index],
// width: 30,
// height: 30,
// fit: BoxFit.contain,
// ),
// SizedBox(
// height: 1.h,
// ),
// Text(
// text,
// style: TextStyle(
// fontSize: 10.sp,
// fontWeight: MyFontWeight.semi_bold,
// color: Color(isSelected ? 0xFF4C4C4C : 0xFFA29E9E),
// ),
// ),
// ],
// ),
// crossFadeState: isSelected
// ? CrossFadeState.showFirst
// : CrossFadeState.showSecond,
// ),
// ),
// ),
// flex: 1,
// );
// }
4 years ago
}