Flutter 自定义入口(DartEntrypoint)
2023-12-25 本文已影响0人
苹果农
不想执行 main 函数,而是想把入口函数换成别的, 方法如下:
Android:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
// 导入 flutter 相关的类
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngineGroup;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint;
import io.flutter.embedding.engine.loader.FlutterLoader;
import io.flutter.FlutterInjector;
public class MainActivity extends Activity {
FlutterEngine flutterEngine;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
runMain2();
}
void runMain2() {
Log.d("main", "runMain2()");
Context context = this.getBaseContext();
FlutterEngineGroup group = new FlutterEngineGroup(context);
FlutterLoader flutterLoader = FlutterInjector.instance().flutterLoader();
// DartEntrypoint entrypoint = new DartEntrypoint(flutterLoader.findAppBundlePath(), "main2");
DartEntrypoint entrypoint = new DartEntrypoint(null, "main2");
flutterEngine = group.createAndRunEngine(context, entrypoint);
}
}
iOS:
FlutterEngineGroup *group = [[FlutterEngineGroup alloc] initWithName:@"main" project:nil];
FlutterEngine *engine = [group makeEngineWithEntrypoint:@"main2" libraryURI:nil];
[engine run];