Flutter 用 plugin 实现 想嵌套 iOS、Android 原生页面 写个demo

动态 未结 0 121
小小草
小小草 LV1 2023年9月23日 23:40 发表
Sure, here's a simple demo that shows how to use a Flutter plugin to embed native iOS and Android views in a Flutter app: 1. Create a new Flutter plugin project using the `flutter create --template=plugin` command. 2. In the plugin project, add the following code to the `ios/Classes/MyNativeView.swift` file to create a native iOS view: ``` import UIKit public class MyNativeView: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .red } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } ``` 3. Add the following code to the `android/src/main/java/com/example/my_plugin/MyNativeView.java` file to create a native Android view: ``` package com.example.my_plugin; import android.content.Context; import android.view.View; import android.widget.TextView; public class MyNativeView extends TextView { public MyNativeView(Context context) { super(context); setBackgroundColor(0xFFFF0000); // red background color setText("Hello from Android!"); // display some text } } ``` 4. Define a platform view factory in the plugin's main Dart file (`lib/my_plugin.dart`) that creates the native views for each platform: ``` import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class MyNativeView extends StatefulWidget { const MyNativeView({Key? key}) : super(key: key); @override _MyNativeViewState createState() => _MyNativeViewState(); } class _MyNativeViewState extends State { late final MethodChannel _channel; @override void initState() { super.initState(); _channel = MethodChannel('my_plugin'); } @override Widget build(BuildContext context) { if (defaultTargetPlatform == TargetPlatform.iOS) { return UiKitView( viewType: 'MyNativeView', creationParams: {}, creationParamsCodec: const StandardMessageCodec(), ); } else if (defaultTargetPlatform == TargetPlatform.android) { return AndroidView( viewType: 'MyNativeView', creationParams: {}, creationParamsCodec: const StandardMessageCodec(), ); } else { return Text('Unsupported platform'); } } } class
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复