Flutter Plugin的坑

1 iOS编译没问题,但是运行时找不到Plugin

@implementation AppDelegate 
    
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  // Plugin注册方法 
  [GeneratedPluginRegistrant registerWithRegistry:self];    
    
  // 显示Window   
  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    
    [self.window setRootViewController:[[FlutterViewController alloc] initWithNibName:nil bundle:nil]]];    
  [self.window setBackgroundColor:[UIColor whiteColor]];    
  [self.window makeKeyAndVisible];      
    
  return [super application:application didFinishLaunchingWithOptions:launchOptions];   
}   
@end

[GeneratedPluginRegistrant registerWithRegistry:self]默认注册到self.window.rootViewController的。所以需要先初始化rootViewController,再注册Plugin。

iOS Plugin注册到指定的FlutterViewController

如果Window的rootViewController不是FlutterViewController,直接注册Plugin会注册失败。我们需要将Plugin注册到指定的FlutterViewController。

#import <UIKit/UIKit.h>
#import <Flutter/Flutter.h>

@interface ViewController : FlutterViewController
@end
@interface ViewController ()
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) FlutterEngine *flutterEngine;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [GeneratedPluginRegistrant registerWithRegistry:[self pluginRegistry]];
    
    __weak __typeof(self) weakSelf = self;
    // 要与main.dart中一致
    NSString *channelName = @"com.123";
    FlutterMethodChannel *messageChannel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:self];
    [messageChannel setMethodCallHandler:^(FlutterMethodCall* _Nonnull call, FlutterResult  _Nonnull result) {
        // call.method 获取 flutter 给回到的方法名,要匹配到 channelName 对应的多个 发送方法名,一般需要判断区分
        // call.arguments 获取到 flutter 给到的参数,(比如跳转到另一个页面所需要参数)
        // result 是给flutter的回调, 该回调只能使用一次
        NSLog(@"flutter 给到我:\nmethod=%@ \narguments = %@",call.method,call.arguments);
        
        if([call.method isEqualToString:@"iOSFlutter"]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"flutter回调" message:[NSString stringWithFormat:@"%@",call.arguments] delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil];
            [alertView show];
            // 回调给flutter
            if (result) {
                result(@1000);
            }
        } else {
            result(FlutterMethodNotImplemented);
        }
    }];
}

@end

Native调用Flutter失败

Flutter App启动后,Native调用Flutter失败?
这是因为Plugin Channel的初始化大概要1.5秒,而且这是一个异步过程。虽然Flutter页面显示出来了,但是Plugin Channel还没初始化完,所以这时Native调用Flutter是没反应的。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容