我們在進行Flutter開發的時候,有時候是需要用到原生的View,比如WebView、MapView、第三方廣告SDK等,Flutter提供了AndroidView、UiKitView可以實現相關功能。
創建項目
這里以在Flutter顯示原生的TextView為案例,展示如何實現,創建項目過程這里不展示,建議使用Android Studio進行開發。
編寫平台相關的代碼
Android
創建PlatformView類
class AndroidTextView(context: Context) : PlatformView { val contentView: TextView = TextView(context) override fun getView(): View { return contentView } override fun dispose() {} }
創建PlatformViewFactory類
class AndroidTextViewFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
val androidTextView = AndroidTextView(context)
androidTextView.contentView.id = viewId
val params = args?.let { args as Map<*, *> } val text = params?.get("text") as CharSequence? text?.let { androidTextView.contentView.text = it } return androidTextView } }
注冊工廠,不同版本的注冊方式有所不同,這里是1.12.13版本
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
val registry = flutterEngine.platformViewsController.registry
registry.registerViewFactory("platform_text_view", AndroidTextViewFactory())
}
}
iOS
第一步:在info.plist增加io.flutter.embedded_views_preview=true,至關重要。
第二步:創建 PlatformTextView.swift
import Foundation
import Flutter
class PlatformTextView: NSObject,FlutterPlatformView {
let frame: CGRect;
let viewId: Int64;
var text:String = ""
init(_ frame: CGRect,viewID: Int64,args :Any?) {
self.frame = frame
self.viewId = viewID
if(args is NSDictionary){
let dict = args as! NSDictionary
self.text = dict.value(forKey: "text") as! String
}
}
func view() -> UIView {
let label = UILabel()
label.text = self.text
label.textColor = UIColor.red
label.frame = self.frame
return label
}
}
第三步:創建PlatformTextViewFactory.swift
import Foundation import Flutter class PlatformTextViewFactory: NSObject,FlutterPlatformViewFactory { func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView { return PlatformTextView(frame,viewID: viewId,args: args) } func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol { return FlutterStandardMessageCodec.sharedInstance() } }
第四步:在 AppDelegate.swift 注冊
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let factory = PlatformTextViewFactory()
let registrar = self.registrar(forPlugin: "platform_text_view_plugin")
registrar.register(factory, withId: "platform_text_view")
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
vi設計http://www.maiqicn.com 辦公資源網站大全https://www.wode007.com
編寫Flutter代碼
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { Widget getPlatformTextView() { if (defaultTargetPlatform == TargetPlatform.android) { return AndroidView( viewType: "platform_text_view", creationParams: <String, dynamic>{"text": "Android Text View"}, creationParamsCodec: const StandardMessageCodec()); } else if (defaultTargetPlatform == TargetPlatform.iOS) { return UiKitView( viewType: "platform_text_view", creationParams: <String, dynamic>{"text": "iOS Label"}, creationParamsCodec: const StandardMessageCodec()); } else { return Text("Not supported"); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body:getPlatformTextView(), ); } }