Android 原生项目集成 Flutter
要在Android原生项目中集成Flutter,你需要按照以下步骤操作:
- 将Flutter模块添加到现有的Android项目中。
- 配置Gradle脚本以构建和嵌入Flutter模块。
- 初始化并运行Flutter引擎。
- 创建Flutter的活动和视图。
以下是一个简化的示例代码,展示了如何在Android项目中集成Flutter:
import io.flutter.embedding.android.FlutterView;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.PluginRegistry;
public class MainActivity extends AppCompatActivity implements PluginRegistry.PluginRegistrantCallback {
private FlutterEngine flutterEngine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化Flutter引擎
flutterEngine = new FlutterEngine(this);
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
flutterEngine.getPlugins().add(new io.flutter.plugins.flutter_plugin.FlutterPlugin());
// 创建Flutter视图并附加到Activity
FlutterView flutterView = new FlutterView(this);
setContentView(flutterView);
// 将Flutter引擎附加到Flutter视图
flutterView.setFlutterEngine(flutterEngine);
}
@Override
public void onStart() {
super.onStart();
if (flutterEngine != null) {
flutterEngine.getLifecycleChannel().appIsInForeground(true);
}
}
@Override
public void onStop() {
super.onStop();
if (flutterEngine != null) {
flutterEngine.getLifecycleChannel().appIsInForeground(false);
}
}
@Override
public void registerWith(PluginRegistry registry) {
// 注册所需的Flutter插件
GeneratedPluginRegistrant.registerWith(this);
}
}
在AndroidManifest.xml
中添加所需的权限和Flutter相关的Activity配置:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<!-- 添加FlutterActivity配置 -->
<application
...>
...
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- 添加用于指示Flutter将其用作主入口点的intent过滤器 -->
<intent-filter>
评论已关闭