首页 > 解决方案 > 如何在 Swift 本机代码中从 Flutter 调用参数?

问题描述

我正在尝试在 Flutter 中使用 PlatformViews 在我的 Flutter 应用程序中本地显示 Swift 代码,但是我的应用程序因当前代码而崩溃。

这是我的 AppDelegate 目前我正在调用我的方法通道:

import Foundation

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, TJPlacementDelegate {
    var p = TJPlacement()
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        let channelName = "NativeView"
        let rootViewController : FlutterViewController = window?.rootViewController as! FlutterViewController
        let methodChannel = FlutterMethodChannel(name: channelName, binaryMessenger: rootViewController as! FlutterBinaryMessenger)
        methodChannel.setMethodCallHandler {(call: FlutterMethodCall, result: FlutterResult) -> Void in
            if (call.method == "setDebugEnabled") {
                let isDebug = call.arguments as! Bool
                Tapjoy.setDebugEnabled(isDebug)
            } 
        }
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

这是我的原生代码的 Dart 实现:

 import 'package:flutter/material.dart';
 import 'tapjoy.dart';

    class Home extends StatefulWidget {
      @override
      _HomeState createState() => _HomeState();
    }

    class _HomeState extends State<Home> {
      @override
      void initState() {
        callTapjoy();
        super.initState();
      }

      Widget build(context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Test'),
            ),
            body: UiKitView(viewType: 'NativeView'),
          ),
        );
      }

      void callTapjoy() {
        Tapjoy.setDebugEnabled(true);
      }
    }

//My code in tapjoy.dart
    class Tapjoy {
      static const MethodChannel _channel = const MethodChannel('NativeView');
          static void setDebugEnabled(bool isDebug) {
        _channel.invokeMethod('setDebugEnabled', {"isDebug": isDebug});
      } 
    } 

我的应用程序崩溃并在调试控制台中显示错误:

Could not cast value of type '__NSDictionaryM' (0x7fff87a61d78) to 'NSNumber' (0x7fff87b1eb08).
2020-04-29 16:56:42.985269+0530 Runner[18484:224162] Could not cast value of type '__NSDictionaryM' (0x7fff87a61d78) to 'NSNumber' (0x7fff87b1eb08).

在此处输入图像描述

标签: iosswiftflutterdart

解决方案


您正在将 a Mapfrom Dart 传递给 native: {"isDebug": isDebug},因此您需要在 Swift 端从地图/字典中提取参数。

  if let args = call.arguments as? Dictionary<String, Any>,
    let isDebug = args["isDebug"] as? Bool {
      // please check the "as" above  - wasn't able to test
      // handle the method

    result(nil)
  } else {
    result(FlutterError.init(code: "errorSetDebug", message: "data or format error", details: nil))
  }

或者,只需从 Dart 端传递布尔值,而无需先将其放入地图中。

_channel.invokeMethod('setDebugEnabled', isDebug);

推荐阅读