当前位置:   article > 正文

Flutter Platform View:在 Flutter 中使用Android、iOS的原生 View

flutter v2 androidview

code小生 一个专注大前端领域的技术平台公众号回复Android加入安卓技术群

作者:ImWiki
链接:https://www.jianshu.com/p/8d74a7318c26
声明:本文已获ImWiki授权发表,转发等请联系原作者授权

我们在进行Flutter开发的时候,有时候是需要用到原生的View,比如WebView、MapView、第三方广告SDK等,Flutter提供了AndroidView、UiKitView可以实现相关功能。

创建项目

这里以在Flutter显示原生的TextView为案例,展示如何实现,创建项目过程这里不展示,建议使用Android Studio进行开发。

编写平台相关的代码

Android

创建PlatformView类

  1. class AndroidTextView(context: Context) : PlatformView {
  2. val contentView: TextView = TextView(context)
  3. override fun getView(): View {
  4. return contentView
  5. }
  6. override fun dispose() {}
  7. }

创建PlatformViewFactory类

  1. class AndroidTextViewFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
  2. override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
  3. val androidTextView = AndroidTextView(context)
  4. androidTextView.contentView.id = viewId
  5. val params = args?.let { args as Map<*, *> }
  6. val text = params?.get("text") as CharSequence?
  7. text?.let {
  8. androidTextView.contentView.text = it
  9. }
  10. return androidTextView
  11. }
  12. }

注册工厂,不同版本的注册方式有所不同,这里是1.12.13版本

  1. class MainActivity : FlutterActivity() {
  2. override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
  3. GeneratedPluginRegistrant.registerWith(flutterEngine)
  4. val registry = flutterEngine.platformViewsController.registry
  5. registry.registerViewFactory("platform_text_view", AndroidTextViewFactory())
  6. }
  7. }
iOS

第一步:在info.plist增加io.flutter.embedded_views_preview=true,至关重要。

第二步:创建 PlatformTextView.swift

  1. import Foundation
  2. import Flutter
  3. class PlatformTextView: NSObject,FlutterPlatformView {
  4. let frame: CGRect;
  5. let viewId: Int64;
  6. var text:String = ""
  7. init(_ frame: CGRect,viewID: Int64,args :Any?) {
  8. self.frame = frame
  9. self.viewId = viewID
  10. if(args is NSDictionary){
  11. let dict = args as! NSDictionary
  12. self.text = dict.value(forKey: "text") as! String
  13. }
  14. }
  15. func view() -> UIView {
  16. let label = UILabel()
  17. label.text = self.text
  18. label.textColor = UIColor.red
  19. label.frame = self.frame
  20. return label
  21. }
  22. }

第三步:创建PlatformTextViewFactory.swift

  1. import Foundation
  2. import Flutter
  3. class PlatformTextViewFactory: NSObject,FlutterPlatformViewFactory {
  4. func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
  5. return PlatformTextView(frame,viewID: viewId,args: args)
  6. }
  7. func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
  8. return FlutterStandardMessageCodec.sharedInstance()
  9. }
  10. }

第四步:在 AppDelegate.swift 注册

  1. @UIApplicationMain
  2. @objc class AppDelegate: FlutterAppDelegate {
  3. override func application(
  4. _ application: UIApplication,
  5. didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  6. ) -> Bool {
  7. GeneratedPluginRegistrant.register(with: self)
  8. let factory = PlatformTextViewFactory()
  9. let registrar = self.registrar(forPlugin: "platform_text_view_plugin")
  10. registrar.register(factory, withId: "platform_text_view")
  11. return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  12. }
  13. }

编写Flutter代码

  1. import 'package:flutter/foundation.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. void main() => runApp(MyApp());
  5. class MyApp extends StatelessWidget {
  6. @override
  7. Widget build(BuildContext context) {
  8. return MaterialApp(
  9. title: 'Flutter Demo',
  10. theme: ThemeData(
  11. primarySwatch: Colors.blue,
  12. ),
  13. home: MyHomePage(title: 'Flutter Demo Home Page'),
  14. );
  15. }
  16. }
  17. class MyHomePage extends StatefulWidget {
  18. MyHomePage({Key key, this.title}) : super(key: key);
  19. final String title;
  20. @override
  21. _MyHomePageState createState() => _MyHomePageState();
  22. }
  23. class _MyHomePageState extends State<MyHomePage> {
  24. Widget getPlatformTextView() {
  25. if (defaultTargetPlatform == TargetPlatform.android) {
  26. return AndroidView(
  27. viewType: "platform_text_view",
  28. creationParams: <String, dynamic>{"text": "Android Text View"},
  29. creationParamsCodec: const StandardMessageCodec());
  30. } else if (defaultTargetPlatform == TargetPlatform.iOS) {
  31. return UiKitView(
  32. viewType: "platform_text_view",
  33. creationParams: <String, dynamic>{"text": "iOS Label"},
  34. creationParamsCodec: const StandardMessageCodec());
  35. } else {
  36. return Text("Not supported");
  37. }
  38. }
  39. @override
  40. Widget build(BuildContext context) {
  41. return Scaffold(
  42. appBar: AppBar(
  43. title: Text(widget.title),
  44. ),
  45. body:getPlatformTextView(),
  46. );
  47. }
  48. }

运行

完整代码

https://github.com/taoweiji/FlutterPlatformViewExample

参考

https://60devs.com/how-to-add-native-code-to-flutter-app-using-platform-views-android.html

相关阅读

1 Flutter1.12 升级后的问题
2 Flutter 实现 App 内更新安装包
3 面对Flutter,我终于迈出了第一步
4 使用Flutter一年后,这是我得到的经验
5 Flutter 与原生交互总结

如果你有写博客的好习惯

欢迎投稿

点个在看,小生感恩❤️

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/425719
推荐阅读
相关标签
  

闽ICP备14008679号