基础组件库
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

481 linhas
15 KiB

  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:ui';
  5. import 'package:cached_network_image/cached_network_image.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:fluttertoast/fluttertoast.dart';
  8. import 'package:more_picture_share/more_picture_share.dart';
  9. import 'package:path_provider/path_provider.dart';
  10. import 'package:permission_handler/permission_handler.dart';
  11. import 'package:share_extend/share_extend.dart';
  12. import 'package:sharesdk_plugin/sharesdk_plugin.dart';
  13. import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/intellect_create.dart';
  14. import 'package:zhiying_base_widget/dialog/global_dialog/notification_setting_dialog/notification_setting_dialog.dart';
  15. import 'package:zhiying_base_widget/dialog/loading/loading.dart';
  16. import 'package:zhiying_base_widget/utils/image_download_util/image_download_util.dart';
  17. import 'package:zhiying_base_widget/widgets/share/models/share_alert_model.dart';
  18. import 'package:zhiying_base_widget/widgets/share/models/share_data_model.dart';
  19. import 'package:zhiying_base_widget/widgets/share/models/share_icon_model.dart';
  20. import 'package:zhiying_base_widget/widgets/share/share_alert_content.dart';
  21. import 'package:zhiying_comm/zhiying_comm.dart';
  22. import 'dart:io';
  23. class ShareAlert extends StatefulWidget {
  24. final String skipIdentifier;
  25. final bool isContentShow;
  26. final ShareDataModel model;
  27. const ShareAlert(this.model, this.skipIdentifier, {Key key, this.isContentShow = false}) : super(key: key); // 中间视图
  28. @override
  29. _ShareAlertState createState() => _ShareAlertState();
  30. }
  31. class _ShareAlertState extends State<ShareAlert> {
  32. ShareAlertModel _iconModel;
  33. @override
  34. void initState() {
  35. Logger.log('设置分享页面不弹');
  36. /// 设置分享页面不弹
  37. IntellectCreate.setCheck(false);
  38. NetUtil.request('/api/v1/mod/${widget.skipIdentifier}', method: NetMethod.GET, onCache: (data) {
  39. // try{
  40. // _parseData(data);
  41. // }catch(e){
  42. // print(e);
  43. // }
  44. }, onSuccess: (data) {
  45. print(data);
  46. _parseData(data);
  47. }, onError: (err) {});
  48. super.initState();
  49. }
  50. @override
  51. void dispose() {
  52. Logger.log('设置智能弹窗可以弹');
  53. /// 之后可以弹
  54. IntellectCreate.setCheck(true);
  55. super.dispose();
  56. }
  57. void _parseData(Map<String, dynamic> data) {
  58. List modList = data['mod_list'];
  59. Map d = modList.first;
  60. if (d != null) {
  61. String dString = d['data'];
  62. _iconModel = ShareAlertModel.fromJson(Map<String, dynamic>.from(jsonDecode(dString)));
  63. setState(() {});
  64. }
  65. }
  66. @override
  67. Widget build(BuildContext context) {
  68. return WillPopScope(
  69. onWillPop: () async {
  70. Loading.dismiss();
  71. Navigator.canPop(context);
  72. return true;
  73. },
  74. child: GestureDetector(
  75. child: Scaffold(
  76. backgroundColor: Colors.transparent,
  77. body: BackdropFilter(
  78. filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), //背景
  79. child: Container(
  80. child: Column(
  81. children: <Widget>[
  82. Expanded(
  83. child: Center(child: widget.isContentShow ? ShareAlertContent(_iconModel) : Container()),
  84. ),
  85. _ShareAlertContent(widget.model, widget.skipIdentifier, _iconModel),
  86. ],
  87. ),
  88. ), // 模糊化
  89. ),
  90. ),
  91. onTap: () {
  92. Navigator.of(context).pop();
  93. },
  94. ),
  95. );
  96. }
  97. }
  98. class _ShareAlertContent extends StatefulWidget {
  99. final ShareDataModel model;
  100. final String skipIdentifier;
  101. final ShareAlertModel iconModel;
  102. const _ShareAlertContent(this.model, this.skipIdentifier, this.iconModel, {Key key}) : super(key: key);
  103. @override
  104. _ShareAlertContentState createState() => _ShareAlertContentState();
  105. }
  106. class _ShareAlertContentState extends State<_ShareAlertContent> {
  107. @override
  108. void initState() {
  109. super.initState();
  110. }
  111. @override
  112. Widget build(BuildContext context) {
  113. return GestureDetector(
  114. onTap: () {},
  115. child: Container(
  116. width: double.infinity,
  117. decoration: BoxDecoration(
  118. color: Colors.white,
  119. borderRadius: BorderRadius.only(
  120. topLeft: Radius.circular(12),
  121. topRight: Radius.circular(12),
  122. ),
  123. ),
  124. child: SafeArea(
  125. top: false,
  126. child: Column(
  127. children: <Widget>[
  128. Container(
  129. margin: EdgeInsets.only(top: 8, bottom: 8),
  130. width: 62,
  131. height: 4,
  132. decoration: BoxDecoration(color: Color(0xffd8d8d8), borderRadius: BorderRadius.circular(2)),
  133. ),
  134. Text(
  135. '分享至',
  136. style: TextStyle(fontSize: 15, color: Color(0xff333333), fontWeight: FontWeight.bold),
  137. ),
  138. Container(
  139. margin: EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
  140. child: _createIcons(),
  141. ),
  142. GestureDetector(
  143. child: Container(
  144. margin: EdgeInsets.only(left: 12, right: 12, bottom: 10),
  145. padding: EdgeInsets.all(12),
  146. decoration: BoxDecoration(color: Color(0xfff3f3f3), borderRadius: BorderRadius.circular(8)),
  147. child: Center(
  148. child: Text(
  149. '取消',
  150. style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Color(0xff999999)),
  151. ),
  152. ),
  153. ),
  154. onTap: () {
  155. Navigator.of(context).pop();
  156. },
  157. )
  158. ],
  159. ),
  160. ),
  161. ),
  162. );
  163. }
  164. Widget _createIcons() {
  165. return Wrap(
  166. spacing: 10,
  167. runSpacing: 10,
  168. children: widget.iconModel?.icons?.map((item) {
  169. return _createIcon(item);
  170. })?.toList() ??
  171. [],
  172. );
  173. }
  174. Widget _createIcon(ShareIconModel item) {
  175. return GestureDetector(
  176. child: Container(
  177. width: 60,
  178. child: Column(
  179. children: <Widget>[
  180. Container(
  181. width: 40,
  182. height: 40,
  183. child: CachedNetworkImage(
  184. imageUrl: item.icon,
  185. fit: BoxFit.contain,
  186. ),
  187. ),
  188. Padding(
  189. padding: const EdgeInsets.only(top: 2, bottom: 2),
  190. child: Text(
  191. item.name,
  192. style: TextStyle(fontSize: 12, color: Color(0xff333333), fontWeight: FontWeight.bold),
  193. ),
  194. ),
  195. ],
  196. ),
  197. ),
  198. onTap: () async {
  199. //检查是否有存储权限
  200. var status = await Permission.storage.status;
  201. if (!status.isGranted) {
  202. var result = await showDialog(context: context, child: NotificationSettingDialogNew([NotificationSettingDialogNew.storagePermissModel]));
  203. if (result != null && result) {
  204. await Permission.storage.request();
  205. if (await Permission.storage.isPermanentlyDenied) {
  206. openAppSettings();
  207. return;
  208. }
  209. } else {
  210. return;
  211. }
  212. }
  213. int count = 0;
  214. if (widget.model.poster != null) {
  215. count++;
  216. }
  217. count += (widget.model?.image?.length ?? 0);
  218. // 多图分享
  219. if (count > 1) {
  220. _shareMultipleImages(item.type);
  221. return;
  222. }
  223. if (widget?.model?.poster != null) {
  224. Loading.show(context);
  225. File file = await EncodeUtil.compressImage(context, images: widget?.model?.poster, size: 600);
  226. widget?.model?.poster = await file.readAsBytes();
  227. Loading.dismiss();
  228. }
  229. if (item.type == 'wx') {
  230. _shareByMob(ShareSDKPlatforms.wechatSession);
  231. } else if (item.type == 'pyq') {
  232. _shareByMob(ShareSDKPlatforms.wechatTimeline);
  233. } else if (item.type == 'qq') {
  234. _shareByMob(ShareSDKPlatforms.qq);
  235. } else if (item.type == 'qq_space') {
  236. _shareByMob(ShareSDKPlatforms.qZone);
  237. } else if (item.type == 'weibo') {
  238. _shareByMob(ShareSDKPlatforms.sina);
  239. } else if (item.type == 'more_setting') {
  240. _shareBySystem(item.type);
  241. }
  242. },
  243. );
  244. }
  245. // mob分享,只能单图分享,多图分享调用系统分享
  246. void _shareByMob(ShareSDKPlatform plateform) async {
  247. Loading.show(context);
  248. Timer(Duration(milliseconds: 2000), () {
  249. Loading.dismiss();
  250. });
  251. SSDKMap params;
  252. if (widget.model.poster != null) {
  253. String path = await _savePoster();
  254. if (path != null && path != '') {
  255. params = SSDKMap()
  256. ..setGeneral(
  257. widget.model?.title ?? '图片分享',
  258. widget.model?.content ?? '更多好事物',
  259. Platform.isIOS ? path : null,
  260. null,
  261. Platform.isAndroid ? path : null,
  262. null,
  263. null,
  264. null,
  265. null,
  266. null,
  267. SSDKContentTypes.image,
  268. );
  269. }
  270. } else {
  271. var type = SSDKContentTypes.auto;
  272. if ((widget?.model?.image?.length ?? 0) != 0 && widget.model?.url != null) {
  273. type = SSDKContentTypes.webpage;
  274. } else if ((widget?.model?.image?.length ?? 0) != 0) {
  275. type = SSDKContentTypes.image;
  276. } else if (widget?.model?.title != null || widget.model?.content != null) {
  277. type = SSDKContentTypes.text;
  278. } else if (widget?.model?.poster != null) {
  279. type = SSDKContentTypes.image;
  280. }
  281. if (plateform == ShareSDKPlatforms.qZone && widget?.model?.content != null) {
  282. widget?.model?.title = null;
  283. widget?.model?.image = [];
  284. widget?.model?.url = null;
  285. type = SSDKContentTypes.message;
  286. }
  287. var isExistImage = false;
  288. if (widget?.model?.image != null && widget?.model?.image?.length > 0) {
  289. isExistImage = true;
  290. }
  291. if (plateform == ShareSDKPlatforms.qq && widget?.model?.url != null) {
  292. SSDKMap params = SSDKMap()
  293. ..setQQ(
  294. widget?.model?.content ?? "",
  295. widget?.model?.title ?? "",
  296. null,
  297. null,
  298. null,
  299. null,
  300. null,
  301. null,
  302. null,
  303. (isExistImage ? widget?.model?.image?.first : null),
  304. null,
  305. widget?.model?.content ?? "",
  306. null,
  307. null,
  308. SSDKContentTypes.image,
  309. ShareSDKPlatforms.qq,
  310. );
  311. SharesdkPlugin.share(ShareSDKPlatforms.qq, params, (SSDKResponseState state, Map userdata, Map contentEntity, SSDKError error) {});
  312. return;
  313. }
  314. params = SSDKMap()
  315. ..setGeneral(
  316. widget.model?.title ?? '~',
  317. widget?.model?.content ?? '~',
  318. Platform.isIOS ? widget.model.image : null,
  319. Platform.isAndroid ? (isExistImage ? widget?.model?.image?.first : null) : null,
  320. null,
  321. widget.model.url,
  322. null,
  323. null,
  324. null,
  325. null,
  326. type,
  327. );
  328. }
  329. var isExistImage = false;
  330. if (widget?.model?.image != null && widget?.model?.image?.length > 0) {
  331. isExistImage = true;
  332. }
  333. ///新浪分享图片
  334. if (plateform == ShareSDKPlatforms.sina &&
  335. (isExistImage || widget?.model?.poster != null) &&
  336. EmptyUtil.isEmpty(widget?.model?.content) &&
  337. EmptyUtil.isEmpty(widget?.model?.url)) {
  338. SSDKMap params2 = SSDKMap()
  339. ..setSina(
  340. "图片分享",
  341. null,
  342. null,
  343. null,
  344. null,
  345. null,
  346. null,
  347. null,
  348. false,
  349. (isExistImage ? widget?.model?.image.first : null),
  350. params.map["imagePath_android"],
  351. SSDKContentTypes.image,
  352. );
  353. print(params2);
  354. SharesdkPlugin.share(ShareSDKPlatforms.sina, params2, (SSDKResponseState state, Map userdata, Map contentEntity, SSDKError error) {});
  355. return;
  356. }
  357. SharesdkPlugin.share(plateform, params, (SSDKResponseState state, Map userdata, Map contentEntity, SSDKError error) {
  358. print(error);
  359. if (state == SSDKResponseState.Fail) {
  360. Fluttertoast.showToast(msg: '分享失败');
  361. } else if (state == SSDKResponseState.Success) {
  362. //Fluttertoast.showToast(msg: '分享成功');
  363. } else if (state == SSDKResponseState.Cancel) {
  364. Fluttertoast.showToast(msg: '取消分享');
  365. }
  366. Logger.debug('${state}, ${error.rawData}');
  367. Loading.dismiss();
  368. });
  369. }
  370. // 系统分享,只能分享图片或者文字,不能组合分享
  371. void _shareBySystem(String type) async {
  372. int count = 0;
  373. if (widget.model.poster != null) {
  374. count++;
  375. }
  376. count += (widget.model?.image?.length ?? 0);
  377. // 多图分享
  378. if (count > 1) {
  379. _shareMultipleImages(type);
  380. return;
  381. }
  382. if (widget.model.poster != null) {
  383. String path = await _savePoster();
  384. if (path != null && path != '') {
  385. ShareExtend.share(path, 'image');
  386. }
  387. } else {
  388. ShareExtend.share(widget.model.content, 'text');
  389. }
  390. }
  391. Future<String> _savePoster() async {
  392. String path;
  393. if (widget.model.poster != null) {
  394. // 检查并请求权限
  395. var status = await Permission.storage.status;
  396. if (status != PermissionStatus.granted) {
  397. var result = await showDialog(context: context, child: NotificationSettingDialogNew([NotificationSettingDialogNew.storagePermissModel]));
  398. if (result != null && result) {
  399. status = await Permission.storage.request();
  400. }
  401. }
  402. if (status != PermissionStatus.granted) {
  403. Fluttertoast.showToast(msg: '暂无存储权限,分享失败');
  404. return null;
  405. }
  406. try {
  407. // 保存到本地路径
  408. // final tempDir = await getTemporaryDirectory();
  409. final tempDir = await getApplicationSupportDirectory();
  410. final file = await File('${tempDir.path}/image.png').create();
  411. file.writeAsBytesSync(widget.model.poster);
  412. path = file.path;
  413. Logger.debug(file.path);
  414. } catch (err, s) {
  415. Logger.error(err.toString(), s.toString());
  416. Fluttertoast.showToast(msg: '分享失败');
  417. return null;
  418. }
  419. }
  420. return path;
  421. }
  422. // 多图分享,调用系统分享
  423. void _shareMultipleImages(String type) async {
  424. List<String> paths = List();
  425. String path = await _savePoster();
  426. if (path != null && path != '') {
  427. paths.add(path);
  428. }
  429. Loading.show(context);
  430. List<String> downPaths = await ImageDownloadUtil.download(widget.model.image);
  431. paths.addAll(downPaths);
  432. if (Platform.isAndroid && type == 'wx') {
  433. MorePictureShare.shareWeixinPics(paths);
  434. } else if (Platform.isAndroid && type == 'pyq') {
  435. MorePictureShare.shareWeixinPicsCirlc(paths);
  436. } else {
  437. ShareExtend.shareMultiple(paths, "image", subject: "");
  438. }
  439. Loading.dismiss();
  440. }
  441. }