美文网首页
Flutter和Xcode混编

Flutter和Xcode混编

作者: woniu | 来源:发表于2020-07-20 10:22 被阅读0次

我们做项目的时候难免会遇到flutter和OC或者swift混编的需求,所以本人也尝试着将flutter集成到项目中进行调用,目前已经集成成功,可以做到界面的跳转。下面我们就来详细的说一下具体的步骤吧:

一、Xcode创建Swift项目。

首先我们创建一个Swift的项目,命名为HunHe。

二、创建flutter项目

这里创建flutter项目是关键点,我们通过终端命令行创建。

1、进入到要创建项目的文件夹中,输入如下命令,创建项目名为my_flutter。
bogon:Demo mac$ flutter create --template module my_flutter

稍等片刻,项目创建成功,如下:


251595245082_.pic_hd.jpg

三、在我们的Podfile文件中导入本地的my_flutter

# 添加模块所在路径
flutter_application_path = '../my_flutter'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'HunHe' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!
  # 安装Flutter模块
  install_all_flutter_pods(flutter_application_path)

end

注释:my_flutter项目和HunHe在同一级目录中,所以我们必须要回到上一级目录中用../my_flutter,其中'podhelper.rb至关重要,这里踩过坑。

四、集成flutter到Swift项目中

cd进入到我们的Swift项目中,准备集成my_flutter。

bogon:Demo mac$ cd /Users/mac/Desktop/Demo/HunHe 
bogon:HunHe mac$ pod install
261595245213_.pic_hd.jpg

集成成功。

五、代码调用

1、在AppDelegate导入flutter,然后创建引擎,最终启动引擎。
import UIKit
import Flutter
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    // 1.创建一个FlutterEngine引擎对象
    lazy var flutterEngine = FlutterEngine(name: "my flutter engine")

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 2、启动引擎
        flutterEngine.run()
        return true
    }
}
2、在ViewController中导入import Flutter,然后创建一个按钮,在事件中获取appdelegate中的引擎,利用引擎获取flutterViewController对象,最后用于push或者present。
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        //1、创建一个按钮
          let button = UIButton(type: UIButton.ButtonType.custom)
          button.addTarget(self, action: #selector(showFlutter), for: .touchUpInside)
          button.setTitle("Show Flutter", for: .normal)
          button.frame = CGRect(x: 80, y: 210, width: 160, height: 40)
          button.backgroundColor = UIColor.blue
          self.view.addSubview(button)
        
        
    }
    @objc func showFlutter() {
           // 2.创建FlutterViewController对象(需要先获取flutterEngine)
           let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine;
           let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil);
//           navigationController?.pushViewController(flutterViewController, animated: true);

        present(flutterViewController, animated: true, completion: nil)
    
    }
}

六、OC代码调用如下

1、Appdelegate.h中调用
@import UIKit;
@import Flutter;

@interface AppDelegate : FlutterAppDelegate 
@property (nonatomic,strong) FlutterEngine *flutterEngine;
@end
2、Appdelegate.m中调用
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h> // Used to connect plugins.

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions {
      
  self.flutterEngine = [[FlutterEngine alloc] initWithName:@"my flutter engine"];
  [self.flutterEngine run];
      
  [GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
3、在ViewController.m中,创建按钮,然后调事件- (void)showFlutter
- (void)showFlutter {
    FlutterEngine *flutterEngine =
        ((AppDelegate *)UIApplication.sharedApplication.delegate).flutterEngine;
    FlutterViewController *flutterViewController =
        [[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
    [self presentViewController:flutterViewController animated:YES completion:nil];
}

运行效果如下:

文件.gif
GIF生成网址:https://www.gif.cn/

上面讲述的是原生调用flutter,现在我们了解一下flutter怎么调用原生方法。有些是我们的flutter无法获取的,比如电量、经纬度,所以我们就需要通过原生的方法来获取。这里主要有以下几步。
1、在flutter中通过Dart创建通道名称

 static const platform = const MethodChannel("my/battery");
下面的代码是搭建UI 
 int _result = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Battery"),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Text("当前电池信息: $_result"),
            RaisedButton(
              child: Text("获取电池信息"),
              onPressed: getBatteryInfo,
            )
          ],
        ),
      ),
    );
  }

2、通过platform.invokeMethod调用平台方法。

  void getBatteryInfo() async {
    // 核心代码二
    final int result = await platform.invokeMethod("getBatteryInfo");
    setState(() {
      _result = result;
    });
  }

二、在调用原生页面添加代码有以下几步:
1、获取FlutterViewController
2、获取方法通道也就是"my/battery"

相关文章

网友评论

      本文标题:Flutter和Xcode混编

      本文链接:https://www.haomeiwen.com/subject/nrajhktx.html