基础组件库
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.
 
 
 
 
 

556 lines
18 KiB

  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:typed_data';
  5. import 'dart:ui';
  6. import 'dart:ui' as ui;
  7. import 'package:cached_network_image/cached_network_image.dart';
  8. import 'package:flutter/cupertino.dart';
  9. import 'package:flutter/material.dart';
  10. import 'package:flutter/rendering.dart';
  11. import 'package:flutter/services.dart';
  12. import 'package:flutter_swiper/flutter_swiper.dart';
  13. import 'package:fluttertoast/fluttertoast.dart';
  14. import 'package:more_picture_share/more_picture_share.dart';
  15. import 'package:path_provider/path_provider.dart';
  16. import 'package:permission_handler/permission_handler.dart';
  17. import 'package:share_extend/share_extend.dart';
  18. import 'package:sharesdk_plugin/sharesdk_plugin.dart';
  19. import 'package:zhiying_base_widget/dialog/loading/loading.dart';
  20. import 'package:zhiying_base_widget/utils/image_download_util/image_download_util.dart';
  21. import 'package:zhiying_base_widget/widgets/share/models/share_alert_model.dart';
  22. import 'package:zhiying_base_widget/widgets/share/models/share_data_model.dart';
  23. import 'package:zhiying_base_widget/widgets/share/models/share_icon_model.dart';
  24. import 'package:zhiying_base_widget/widgets/share/share_alert_content.dart';
  25. import 'package:zhiying_comm/zhiying_comm.dart';
  26. import 'package:zhiying_base_widget/widgets/share/models/share_select_pic_model.dart';
  27. import 'package:zhiying_base_widget/template/goods_share_template/goods_share_template.dart';
  28. class ShareAlertSelect extends StatefulWidget {
  29. final String skipIdentifier;
  30. final bool isContentShow;
  31. final ShareDataModel model;
  32. final bool isPicShow;
  33. final ShareSelectPicModel selectPicModel;
  34. const ShareAlertSelect(this.model, this.skipIdentifier,
  35. {Key key, this.isContentShow = false, this.selectPicModel, this.isPicShow})
  36. : super(key: key); // 中间视图
  37. @override
  38. _ShareAlertSelectState createState() => _ShareAlertSelectState();
  39. }
  40. class _ShareAlertSelectState extends State<ShareAlertSelect> {
  41. ShareAlertModel _iconModel;
  42. bool isPicShow;
  43. ShareSelectPicModel selectPicModel;
  44. GlobalKey _globalKey = GlobalKey();
  45. @override
  46. void initState() {
  47. NetUtil.request('/api/v1/mod/${widget.skipIdentifier}', method: NetMethod.GET,
  48. onCache: (data) {
  49. // try{
  50. // _parseData(data);
  51. // }catch(e){
  52. // print(e);
  53. // }
  54. }, onSuccess: (data) {
  55. print(data);
  56. _parseData(data);
  57. }, onError: (err) {});
  58. if (!EmptyUtil.isEmpty(widget.isPicShow)) {
  59. isPicShow = widget.isPicShow;
  60. } else {
  61. isPicShow = false;
  62. }
  63. selectPicModel = widget.selectPicModel;
  64. super.initState();
  65. }
  66. void _parseData(Map<String, dynamic> data) {
  67. List modList = data['mod_list'];
  68. Map d = modList.first;
  69. if (d != null) {
  70. String dString = d['data'];
  71. _iconModel =
  72. ShareAlertModel.fromJson(Map<String, dynamic>.from(jsonDecode(dString)));
  73. setState(() {});
  74. }
  75. }
  76. _selectPic(List<SharePicItem> picList, int position) async {
  77. ShareDataModel model = ShareDataModel();
  78. model.image = [];
  79. for (int i = 0; i < picList.length; i++) {
  80. if (picList[i].select) {
  81. if (i == 0) {
  82. ShareDataModel shareDataModel = await _updateModel(_globalKey);
  83. model.poster = shareDataModel.poster;
  84. } else {
  85. model.image.add(picList[i].pic);
  86. }
  87. }
  88. }
  89. EventUtil.instance.fire(model);
  90. }
  91. Future<ShareDataModel> _updateModel(GlobalKey _globalKey) async {
  92. ShareDataModel _shareModel = ShareDataModel();
  93. BuildContext buildContext = _globalKey.currentContext;
  94. if (null != buildContext) {
  95. RenderRepaintBoundary boundary = buildContext.findRenderObject();
  96. ui.Image image = await boundary.toImage(pixelRatio: 1);
  97. // 注意:png是压缩后格式,如果需要图片的原始像素数据,请使用rawRgba
  98. ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
  99. Uint8List pngBytes = byteData.buffer.asUint8List();
  100. _shareModel.poster = pngBytes;
  101. } else {
  102. _shareModel.poster = null;
  103. }
  104. // _shareModel.content = _isContentSelected ? _content : '';
  105. return _shareModel;
  106. }
  107. @override
  108. Widget build(BuildContext context) {
  109. return WillPopScope(
  110. onWillPop: () async {
  111. Loading.dismiss();
  112. Navigator.canPop(context);
  113. return true;
  114. },
  115. child: GestureDetector(
  116. child: Scaffold(
  117. backgroundColor: Colors.transparent,
  118. body: BackdropFilter(
  119. filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), //背景
  120. child: Container(
  121. child: Column(
  122. children: <Widget>[
  123. widget.isContentShow
  124. ? Expanded(
  125. child: Center(child: ShareAlertContent(_iconModel)),
  126. )
  127. : Container(),
  128. isPicShow
  129. ? Expanded(
  130. child: Swiper(
  131. loop: false,
  132. itemBuilder: (BuildContext context, int index) {
  133. Widget picWidget;
  134. if (index == 0) {
  135. picWidget = Column(
  136. children: [
  137. Expanded(
  138. child: Transform.scale(
  139. alignment: Alignment.center,
  140. scale: 0.75,
  141. child: GoodsShareTemplate(
  142. selectPicModel.posterModel,
  143. contentKey: _globalKey,
  144. ),
  145. ),
  146. ),
  147. ],
  148. );
  149. } else {
  150. picWidget = CachedNetworkImage(
  151. imageUrl: selectPicModel.picList[index].pic,
  152. fit: BoxFit.fitWidth,
  153. );
  154. }
  155. return Container(
  156. alignment: Alignment.bottomCenter,
  157. margin: EdgeInsets.only(top: 50, bottom: 10),
  158. child: Stack(
  159. children: <Widget>[
  160. picWidget,
  161. // CachedNetworkImage(
  162. // imageUrl: selectPicModel.picList[index].pic,
  163. // fit: BoxFit.fitWidth,
  164. // ),
  165. Positioned(
  166. bottom: 10,
  167. right: 15,
  168. child: GestureDetector(
  169. onTap: () {
  170. selectPicModel.picList[index].select =
  171. !selectPicModel.picList[index].select;
  172. setState(() {});
  173. _selectPic(selectPicModel.picList, index);
  174. },
  175. child: Container(
  176. alignment: Alignment.center,
  177. decoration: BoxDecoration(
  178. borderRadius: BorderRadius.circular(50),
  179. color: selectPicModel.picList[index].select
  180. ? Colors.red
  181. : Colors.grey,
  182. ),
  183. child: Icon(
  184. CupertinoIcons.check_mark,
  185. color: Colors.white,
  186. ),
  187. ),
  188. ),
  189. )
  190. ],
  191. ),
  192. );
  193. },
  194. itemCount: selectPicModel.picList.length,
  195. viewportFraction: 0.8,
  196. scale: 0.8,
  197. ),
  198. )
  199. : Container(),
  200. _ShareAlertContent(
  201. widget.model, widget.skipIdentifier, _iconModel, isPicShow),
  202. ],
  203. ),
  204. ), // 模糊化
  205. ),
  206. ),
  207. onTap: () {
  208. // Navigator.of(context).pop();
  209. },
  210. ),
  211. );
  212. }
  213. }
  214. class _ShareAlertContent extends StatefulWidget {
  215. final ShareDataModel model;
  216. final String skipIdentifier;
  217. final ShareAlertModel iconModel;
  218. final bool isSelectPic;
  219. const _ShareAlertContent(
  220. this.model, this.skipIdentifier, this.iconModel, this.isSelectPic,
  221. {Key key})
  222. : super(key: key);
  223. @override
  224. _ShareAlertContentState createState() => _ShareAlertContentState();
  225. }
  226. class _ShareAlertContentState extends State<_ShareAlertContent> {
  227. StreamSubscription listen;
  228. bool isSelectPic;
  229. ShareDataModel _shareDataModel;
  230. @override
  231. void dispose() {
  232. // TODO: implement dispose
  233. listen?.cancel();
  234. super.dispose();
  235. }
  236. @override
  237. void initState() {
  238. // TODO: implement initState
  239. isSelectPic = widget.isSelectPic;
  240. if (isSelectPic) {
  241. _shareDataModel = null;
  242. } else {
  243. _shareDataModel = widget?.model;
  244. }
  245. listen = EventUtil.instance.on<ShareDataModel>().listen((ShareDataModel event) {
  246. if (isSelectPic) {
  247. _shareDataModel = event;
  248. }
  249. });
  250. super.initState();
  251. }
  252. @override
  253. Widget build(BuildContext context) {
  254. return GestureDetector(
  255. onTap: () {},
  256. child: Container(
  257. width: double.infinity,
  258. decoration: BoxDecoration(
  259. color: Colors.white,
  260. borderRadius: BorderRadius.only(
  261. topLeft: Radius.circular(12),
  262. topRight: Radius.circular(12),
  263. ),
  264. ),
  265. child: SafeArea(
  266. top: false,
  267. child: Column(
  268. children: <Widget>[
  269. Container(
  270. margin: EdgeInsets.only(top: 8, bottom: 8),
  271. width: 62,
  272. height: 4,
  273. decoration: BoxDecoration(
  274. color: Color(0xffd8d8d8), borderRadius: BorderRadius.circular(2)),
  275. ),
  276. Text(
  277. '分享至',
  278. style: TextStyle(
  279. fontSize: 15, color: Color(0xff333333), fontWeight: FontWeight.bold),
  280. ),
  281. Container(
  282. margin: EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
  283. child: _createIcons(),
  284. ),
  285. GestureDetector(
  286. child: Container(
  287. margin: EdgeInsets.only(left: 12, right: 12, bottom: 10),
  288. padding: EdgeInsets.all(12),
  289. decoration: BoxDecoration(
  290. color: Color(0xfff3f3f3), borderRadius: BorderRadius.circular(8)),
  291. child: Center(
  292. child: Text(
  293. '取消',
  294. style: TextStyle(
  295. fontSize: 12,
  296. fontWeight: FontWeight.bold,
  297. color: Color(0xff999999)),
  298. ),
  299. ),
  300. ),
  301. onTap: () {
  302. Navigator.of(context).pop();
  303. },
  304. )
  305. ],
  306. ),
  307. ),
  308. ),
  309. );
  310. }
  311. Widget _createIcons() {
  312. return Wrap(
  313. spacing: 10,
  314. runSpacing: 10,
  315. children: widget.iconModel?.icons?.map((item) {
  316. return _createIcon(item);
  317. })?.toList() ??
  318. [],
  319. );
  320. }
  321. Widget _createIcon(ShareIconModel item) {
  322. return GestureDetector(
  323. child: Container(
  324. width: 60,
  325. child: Column(
  326. children: <Widget>[
  327. Container(
  328. width: 40,
  329. height: 40,
  330. child: CachedNetworkImage(
  331. imageUrl: item.icon,
  332. fit: BoxFit.contain,
  333. ),
  334. ),
  335. Padding(
  336. padding: const EdgeInsets.only(top: 2, bottom: 2),
  337. child: Text(
  338. item.name,
  339. style: TextStyle(
  340. fontSize: 12, color: Color(0xff333333), fontWeight: FontWeight.bold),
  341. ),
  342. ),
  343. ],
  344. ),
  345. ),
  346. onTap: () async {
  347. //检查是否有存储权限
  348. var status = await Permission.storage.status;
  349. if (!status.isGranted) {
  350. status = await Permission.storage.request();
  351. print(status);
  352. return;
  353. }
  354. if (item.type == 'wx') {
  355. _shareByMob(ShareSDKPlatforms.wechatSession);
  356. } else if (item.type == 'pyq') {
  357. _shareByMob(ShareSDKPlatforms.wechatTimeline);
  358. } else if (item.type == 'qq') {
  359. _shareByMob(ShareSDKPlatforms.qq);
  360. } else if (item.type == 'qq_space') {
  361. _shareByMob(ShareSDKPlatforms.qZone);
  362. } else if (item.type == 'weibo') {
  363. _shareByMob(ShareSDKPlatforms.sina);
  364. } else if (item.type == 'more_setting') {
  365. _shareBySystem(item.type);
  366. }
  367. },
  368. );
  369. }
  370. // mob分享,只能单图分享,多图分享调用系统分享
  371. void _shareByMob(ShareSDKPlatform plateform) async {
  372. if (isSelectPic &&
  373. EmptyUtil.isEmpty(_shareDataModel) &&
  374. EmptyUtil.isEmpty(_shareDataModel?.poster) &&
  375. EmptyUtil.isEmpty(_shareDataModel?.image)) {
  376. Fluttertoast.showToast(msg: '请选择分享图片');
  377. return;
  378. }
  379. Loading.show(context);
  380. Timer(Duration(milliseconds: 2000), () {
  381. Loading.dismiss();
  382. });
  383. SSDKMap params;
  384. if (_shareDataModel.poster != null) {
  385. String path = await _savePoster();
  386. if (path != null && path != '') {
  387. params = SSDKMap()
  388. ..setGeneral(
  389. _shareDataModel?.title ?? '',
  390. _shareDataModel?.content ?? '',
  391. Platform.isIOS ? path : null,
  392. null,
  393. Platform.isAndroid ? path : null,
  394. null,
  395. null,
  396. null,
  397. null,
  398. null,
  399. SSDKContentTypes.image,
  400. );
  401. }
  402. } else {
  403. var type = SSDKContentTypes.auto;
  404. if (_shareDataModel?.image?.first != null && _shareDataModel?.url != null) {
  405. type = SSDKContentTypes.webpage;
  406. } else if (_shareDataModel?.image?.first != null) {
  407. type = SSDKContentTypes.image;
  408. } else if (_shareDataModel?.title != null || _shareDataModel?.content != null) {
  409. type = SSDKContentTypes.text;
  410. }
  411. if (plateform == ShareSDKPlatforms.qZone && type == SSDKContentTypes.text) {
  412. _shareDataModel?.title = null;
  413. type = SSDKContentTypes.message;
  414. }
  415. params = SSDKMap()
  416. ..setGeneral(
  417. _shareDataModel?.title ?? '',
  418. _shareDataModel?.content ?? '',
  419. Platform.isIOS ? _shareDataModel.image : null,
  420. Platform.isAndroid ? _shareDataModel?.image?.first : null,
  421. null,
  422. _shareDataModel.url,
  423. null,
  424. null,
  425. null,
  426. null,
  427. type,
  428. );
  429. }
  430. SharesdkPlugin.share(plateform, params, (SSDKResponseState state, Map userdata, Map contentEntity, SSDKError error) {
  431. print(error);
  432. if (state == SSDKResponseState.Fail) {
  433. Fluttertoast.showToast(msg: '分享失败');
  434. } else if (state == SSDKResponseState.Success) {
  435. //Fluttertoast.showToast(msg: '分享成功');
  436. } else if (state == SSDKResponseState.Cancel) {
  437. Fluttertoast.showToast(msg: '取消分享');
  438. }
  439. Logger.debug('${state}, ${error.rawData}');
  440. Loading.dismiss();
  441. });
  442. }
  443. // 系统分享,只能分享图片或者文字,不能组合分享
  444. void _shareBySystem(String type) async {
  445. if (isSelectPic &&
  446. EmptyUtil.isEmpty(_shareDataModel) &&
  447. EmptyUtil.isEmpty(_shareDataModel?.poster) &&
  448. EmptyUtil.isEmpty(_shareDataModel?.image)) {
  449. Fluttertoast.showToast(msg: '请选择分享图片');
  450. return;
  451. }
  452. int count = 0;
  453. if (_shareDataModel.poster != null) {
  454. count++;
  455. }
  456. count += (_shareDataModel?.image?.length ?? 0);
  457. // 多图分享
  458. if (count > 1) {
  459. _shareMultipleImages(type);
  460. return;
  461. }
  462. if (_shareDataModel.poster != null) {
  463. String path = await _savePoster();
  464. if (path != null && path != '') {
  465. ShareExtend.share(path, 'image');
  466. }
  467. } else {
  468. ShareExtend.share(_shareDataModel.content, 'text');
  469. }
  470. }
  471. Future<String> _savePoster() async {
  472. String path;
  473. if (_shareDataModel.poster != null) {
  474. // 检查并请求权限
  475. var status = await Permission.storage.status;
  476. if (status != PermissionStatus.granted) {
  477. status = await Permission.storage.request();
  478. }
  479. if (status == PermissionStatus.denied) {
  480. Fluttertoast.showToast(msg: '暂无权限,分享失败');
  481. return null;
  482. }
  483. try {
  484. // 保存到本地路径
  485. final tempDir = await getTemporaryDirectory();
  486. final file = await File('${tempDir.path}/image.jpg').create();
  487. file.writeAsBytesSync(_shareDataModel.poster);
  488. path = file.path;
  489. Logger.debug(file.path);
  490. } catch (err, s) {
  491. Logger.error(err.toString(), s.toString());
  492. Fluttertoast.showToast(msg: '分享失败');
  493. return null;
  494. }
  495. }
  496. return path;
  497. }
  498. // 多图分享,调用系统分享
  499. void _shareMultipleImages(String type) async {
  500. List<String> paths = List();
  501. String path = await _savePoster();
  502. if (path != null && path != '') {
  503. paths.add(path);
  504. }
  505. Loading.show(context);
  506. List<String> downPaths = await ImageDownloadUtil.download(_shareDataModel.image);
  507. paths.addAll(downPaths);
  508. if (Platform.isAndroid && type == 'wx') {
  509. MorePictureShare.shareWeixinPics(paths);
  510. } else if (Platform.isAndroid && type == 'pyq') {
  511. MorePictureShare.shareWeixinPicsCirlc(paths);
  512. } else {
  513. ShareExtend.shareMultiple(paths, "image", subject: "");
  514. }
  515. Loading.dismiss();
  516. }
  517. }