initWebC method

Future initWebC()

Implementation

Future initWebC() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();

  String? htmlPath = prefs.getString(zyg_html_path_key);

  if (htmlPath == null) {
    // final data = await rootBundle
    //     .load('packages/zyg_flutter_plugin/lib/assets/libZygGetKeyJNI.so');
    final data =
        await rootBundle.load('packages/zyg_mqtt_plugin/lib/mqtt/my.html');
    print(data);

    // final data = await rootBundle.load('assets/libZygGetKeyJNI.so');
    final bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    final tempDir = await getApplicationDocumentsDirectory();
    final tempFilePath = '${tempDir.path}/my.html';
    final file = File(tempFilePath);
    await file.writeAsBytes(bytes);

    htmlPath = tempFilePath;

    // String? htmlPath = prefs.getString(zyg_html_path_key);

    prefs.setString(zyg_html_path_key, htmlPath);

    final data2 =
        await rootBundle.load('packages/zyg_mqtt_plugin/lib/mqtt/bundle.js');
    final bytes2 =
        data2.buffer.asUint8List(data2.offsetInBytes, data2.lengthInBytes);
    final tempFilePath2 = '${tempDir.path}/bundle.js';
    final file2 = File(tempFilePath2);
    await file2.writeAsBytes(bytes2);
  }

  webController = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setBackgroundColor(const Color(0x00000000))
    ..setNavigationDelegate(
      NavigationDelegate(
        onProgress: (int progress) {
          // Update loading bar.
        },
        onPageStarted: (String url) {},
        onPageFinished: (String url) {
          isPageFinished = true;
          if (myLoadFinishCallback != null) {
            myLoadFinishCallback!();
          }
        },
        onHttpError: (HttpResponseError error) {},
        onWebResourceError: (WebResourceError error) {},
        onNavigationRequest: (NavigationRequest request) {
          if (request.url.startsWith('https://www.youtube.com/')) {
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ),
    )
    // ..loadRequest(Uri.parse('https://flutter.dev'));
    // ..loadFlutterAsset('lib/mqtt/my.html');
    ..loadFile(htmlPath);
  //添加web到flutter到通道
  webController!.addJavaScriptChannel('h5ToFlutter',
      onMessageReceived: (JavaScriptMessage message) {
    // print(message.message);
    dencodeFromMqtt(message.message);
  });
}