Flutter 和 Android原生(Activity、Fragment)相互跳转、传参
在Flutter和Android原生之间实现互相跳转、传参,可以使用以下方法:
Flutter跳转到原生页面并传参:
使用
MethodChannel
发送方法调用和参数。原生(Activity或Fragment)跳转到Flutter页面:
使用
FlutterView
控件嵌入Flutter,并通过MethodChannel
与Flutter通信。
以下是具体的实现方式:
Flutter跳转到原生页面并传参
在Flutter中:
import 'package:flutter/services.dart';
const platform = MethodChannel('com.example.myapp/navigation');
// 跳转方法,并传递参数
Future<void> goToNativePage(String data) async {
try {
await platform.invokeMethod('goToNativePage', {'data': data});
} on PlatformException catch (e) {
print("Failed to Invoke: '${e.message}'.");
}
}
在Android原生代码中:
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor(), "com.example.myapp/navigation");
methodChannel.setMethodCallHandler((methodCall, result) -> {
if (methodCall.method.equals("goToNativePage")) {
String data = methodCall.argument("data");
// 跳转到原生页面并传递参数data
Intent intent = new Intent(this, NativePageActivity.class);
intent.putExtra("data", data);
startActivity(intent);
}
result.success(true);
});
}
}
原生(Activity或Fragment)跳转到Flutter页面
在Android原生代码中:
import io.flutter.embedding.android.FlutterFragment;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 假设FlutterFragment在activity_main.xml定义
FlutterFragment flutterFragment = (FlutterFragment) getSupportFragmentManager().findFragmentByTag("flutter_fragment");
if (flutterFragment == null) {
评论已关闭