xinhuamm_xycloud 1.3.9 copy "xinhuamm_xycloud: ^1.3.9" to clipboard
xinhuamm_xycloud: ^1.3.9 copied to clipboard

新移云SDK插件

example/lib/main.dart

import 'dart:ffi';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:xinhuamm_xycloud/xinhuamm_xycloud.dart';
import 'package:visibility_detector/visibility_detector.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

final _xinhuammXycloudPlugin = XinhuammXycloud();

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    setCloudGlobalConfig();
    setCloudMethodCallHandler();
  }

  @override
  void dispose() {
    print("生命周期:dispose");
    _tabController.dispose();
    super.dispose();
  }

  @override
  void deactivate() {
    print("生命周期:deactivate");
    super.deactivate();
  }

  @override
  void activate() {
    print("生命周期:activate");
    super.activate();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('新移云SDK Flutter原生插件'),
          actions: [
            IconButton(
              icon: const Icon(Icons.qr_code_scanner), // 图片按钮的图标
              onPressed: () {
                openScanPage();
              },
            ),
          ],
        ),
        body: WillPopScope(
          onWillPop: () async {
            bool handled = await _xinhuammXycloudPlugin.onBackPressed();
            return !handled;
          },
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                  margin: const EdgeInsets.all(6.0),
                  child: ElevatedButton(
                    onPressed: () {
                      // 按钮被点击时的操作
                      openCloudPage();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue, // 按钮的背景颜色
                      textStyle: TextStyle(color: Colors.white), // 文本颜色
                      padding: EdgeInsets.fromLTRB(16.0, 10, 16, 10), // 内边距
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0), // 圆角
                      ),
                    ),
                    child: Text(
                      '打开新移云页面', // 按钮文本
                      style: TextStyle(
                        fontSize: 18.0, // 字体大小
                      ),
                    ),
                  ),
                ),
                const Text('内嵌新移云页面,下面实现tabbar,用于处理生命周期同步问题'),

                // Expanded(
                //   child: Container(
                //       color: Colors.blue,
                //       // 设置背景色
                //       // child: getXYCloudFlutterWebView()
                //   ),
                // ),
                Expanded(
                    child: Column(
                  children: [
                    // 自定义Tab布局
                    Container(
                      color: Colors.blue,
                      child: TabBar(
                        controller: _tabController,
                        tabs: [
                          Tab(text: 'Tab 1'),
                          Tab(text: 'Tab 2'),
                          Tab(text: 'Tab 3'),
                        ],
                      ),
                    ),
                    // Tab对应的内容
                    Expanded(
                      child: TabBarView(
                        controller: _tabController,
                        children: [
                          // Center(child: Text('内容 1')),
                          // getXYCloudFlutterWebView(),
                          MyTabContent(key: UniqueKey()),
                          Center(child: Text('内容 2')),
                          Center(child: Text('内容 3')),
                        ],
                      ),
                    ),
                  ],
                ))
              ],
            ),
          ),
        ),
      ),
    );
  }

  void handleScanResult(String scanResult) async {
    bool handled = await _xinhuammXycloudPlugin.handleScanResult(scanResult);
    if (handled) {
      print("sdk内部已处理,外部无需处理");
    } else {
      print("sdk内部未处理,外部需处理");
    }
  }

  void openScanPage() async {
    String scanResult = await _xinhuammXycloudPlugin.openScanPage();
    print("扫码结果:$scanResult");
  }

  void openCloudPage() {
    _xinhuammXycloudPlugin.openCloudPage(
        // 'https://liveh5-xhyd.cn3x.com.cn/statics/xhmm-live-h5/index.html#/?liveId=8&siteId=8fb4b96c99b743119ffc8748539de765'
        // "http://10.0.20.14:5762/?showStatusBar=2"
        // "https://yc.market.xinhuamm.net/statics/cloud-application-o2o-user-h5/pages/meal-card/home?showStatusBar=2&isHideBack=1"
        // "https://xuancheng.market.xinhuamm.net/statics/cloud-application-o2o-user-h5/?isSpecialMall=1&hideTopView=1&nory=1"
        "https://activity.platform.xinhuaapp.com/statics/out-sdk-test/#/?lesscode=a4207fac62ef4540853b62b50dc721a2"
        // "https://yc.market.xinhuamm.net/statics/cloud-application-o2o-user-h5?nory=1"
        );
  }

  void setCloudGlobalConfig() {
    _xinhuammXycloudPlugin.setCloudGlobalConfig({
      "appId": "ec445803d2e14f82a20ecf38259a58da", // 宜昌正式配置,调试用
      "appKey": "4128955854b4421f943915aa1e730b4d",
      "appSecret": "a6a34bf1ce4b4d0ca84723aebd93e39c",
      "weixinSchemeUrl": "微信支付协议",
      "appUrlScheme": "支付宝支付协议",
      "userAgent": "xinhuamm",
      "themeColor": "#f38242",
      "showNavigationBar": false,
      "isDebug": true
    });
  }

  void setCloudMethodCallHandler() {
    _xinhuammXycloudPlugin.setCloudMethodCallHandler((call) {
      print("客户端调用Flutter端方法:${call.method}>>>参数:${call.arguments}");
      if ("login" == call.method) {
        print("打开登录页");
        Completer<dynamic> completer = Completer<dynamic>();
        // 打开登录页面,注释代码也请仔细查看

        // openLoginPage((String userId) {
        //   // 回调函数,处理登录成功后的逻辑
        //   print("用户登录成功,userId: $userId");
        //   completer.complete({
        //     "userId": "userId",
        //     "userPhone": "userPhone"
        //   });
        //   // 登录取消或登录失败后的逻辑也请回调执行completer,传空即可
        // });

        // 等待Completer完成,将其Future返回
        return completer.future;
      } else if ("getUserInfo" == call.method) {
        // 获取用户标识,判断用户是否登录或切换用户
        /* {
          "userId":"用户标识",
        } */
        print("获取用户标识");
        return Future.value({"userId": 123456, "userPhone": "18511650453"});
        // return Future.value({"userId": "cmj", "userPhone": "17858939680"});
      } else if ("getToken" == call.method) {
        // 获取免登接口请求参数。返回:json字符串
        /* {
          "token":"用户token",
        } */
        print("获取免登信息");
        return Future.value({
          "token": "bfd49b86-7f60-44e0-a87a-9a005e4f8aa2",
          // "token": "用户token",
        });
      } else if ("share" == call.method) {
        // 调用分享功能,call中带有分享参数:
        /* {
        "title":"分享标题",
        "description":"分享摘要",
        "imageUrl":"分享图片",
        "url":"分享链接",
        "platform":"0" //0 -> @"朋友圈" ,1->@"微信好友",2->@"微博",3->@"QQ好友",4->@"QQ空间",5->@"钉钉"
        } */
        String title = call.arguments['title'];
        String description = call.arguments['description'];
        String imageUrl = call.arguments['imageUrl'];
        String url = call.arguments['url'];
        String platform = call.arguments['platform'];
      } else if ("openMini" == call.method) {
        // 打开微信小程序,call中带有小程序信息:code&path
        String code = call.arguments['code'];
        String path = call.arguments['path'];
        print("打开小程序");
      }
      return Future.value(null);
    });
  }
}

class MyTabContent extends StatefulWidget {
  const MyTabContent({Key? key}) : super(key: key);

  @override
  _MyTabContentState createState() => _MyTabContentState();
}

class _MyTabContentState extends State<MyTabContent>
    with AutomaticKeepAliveClientMixin {
  bool isVisible = false;

  @override
  Widget build(BuildContext context) {
    super.build(context); // 保持状态的关键

    return VisibilityDetector(
      key: Key("XYCloudFlutterWebView"),
      onVisibilityChanged: (visibilityInfo) {
        isVisible = visibilityInfo.visibleFraction > 0.0;
        _xinhuammXycloudPlugin.notifyCloudPageVisibility(isVisible);
        print("是否显示$isVisible");
      },
      child: getXYCloudFlutterWebView(),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

Widget getXYCloudFlutterWebView() {
  print("getXYCloudFlutterWebView");
  const String viewType = 'XYCloudFlutterWebView';
  const String url =
      // 'https://xuancheng.market.xinhuamm.net/statics/cloud-application-o2o-user-h5/?isSpecialMall=1&hideTopView=1&nory=1';
      // 'https://yc.market.xinhuamm.net/statics/cloud-application-o2o-user-h5/pages/meal-card/home?showStatusBar=1&isHideBack=1';
  'https://yc.market.xinhuamm.net/statics/cloud-application-o2o-user-h5?nory=1&service_flag=o2o_half_screen';
  const Map<String, dynamic> creationParam = {'url': url};
  const MessageCodec creationParamsCodec = StandardMessageCodec();
  if (defaultTargetPlatform == TargetPlatform.android) {
    return const AndroidView(
      viewType: viewType,
      creationParams: creationParam,
      creationParamsCodec: creationParamsCodec,
    );
  } else if (defaultTargetPlatform == TargetPlatform.iOS) {
    return const UiKitView(
      viewType: viewType,
      creationParams: creationParam,
      creationParamsCodec: creationParamsCodec,
    );
  }
  return Container();
}