以下是一个简单的示例,演示如何在Flutter插件中嵌入原生iOS和Android视图:
1. 在Flutter插件中创建一个新的Flutter页面
```dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class MyFlutterPage extends StatefulWidget {
@override
_MyFlutterPageState createState() => _MyFlutterPageState();
}
class _MyFlutterPageState extends State {
static const platform = MethodChannel('com.example.myplugin/native');
String _nativeMessage = '';
Future _getNativeMessage() async {
String message;
try {
message = await platform.invokeMethod('getNativeMessage');
} on PlatformException catch (e) {
message = "Failed to get native message: '${e.message}'.";
}
setState(() {
_nativeMessage = message;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'This is a Flutter page',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _getNativeMessage,
child: Text('Get Native Message'),
),
SizedBox(height: 20),
Text(_nativeMessage),
],
),
),
);
}
}
```
2. 在iOS原生代码中创建一个UIViewController,并将其添加到FlutterViewController中
```swift
import Flutter
class MyNativeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
label.text = "This is an iOS view"
label.textAlignment = .center
label.center = view.center
view.addSubview(label)
}
}
class MyPlugin: NSObject, FlutterPlugin {
static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "com.example.myplugin/native", binaryMessenger: registrar.messenger())
let instance = MyPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
let viewController =