Flutter Android Embedding: V1 vs V2
Flutter offers two primary approaches for embedding Flutter modules into your Android applications: Embedding V1 and Embedding V2. While both achieve the same goal, they differ in their implementation and provide varying advantages depending on your project requirements.
Understanding Embedding V1
Key Features:
- Based on the
FlutterActivity
andFlutterFragment
classes. - Simple and straightforward integration, ideal for basic Flutter modules.
- Offers less flexibility and control over the Flutter engine.
Understanding Embedding V2
Key Features:
- Introduces the
FlutterEngine
class, managing the Flutter runtime. - Provides greater control over the Flutter engine, enabling multiple Flutter instances within a single Android app.
- More complex to setup but offers higher flexibility and performance.
Comparison Table:
Feature | Embedding V1 | Embedding V2 |
---|---|---|
Implementation | FlutterActivity , FlutterFragment |
FlutterEngine |
Flexibility | Limited | High |
Performance | Good | Potentially better (due to multiple engine support) |
Complexity | Simple | Moderate |
Multiple Flutter Instances | Not Supported | Supported |
Example Code:
Embedding V1 (MainActivity.java):
import io.flutter.embedding.android.FlutterActivity; public class MainActivity extends FlutterActivity {}
Embedding V2 (MainActivity.java):
import io.flutter.embedding.android.FlutterEngine; import io.flutter.embedding.android.FlutterEngineCache; import io.flutter.embedding.android.FlutterView; import io.flutter.plugin.common.MethodChannel; public class MainActivity extends AppCompatActivity { private FlutterEngine flutterEngine; private FlutterView flutterView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); flutterEngine = new FlutterEngine(this); flutterView = FlutterEngineCache.getInstance().get("my_flutter_engine").getFlutterView(); setContentView(flutterView); MethodChannel channel = new MethodChannel(flutterEngine.getDartExecutor(), "my_channel"); channel.setMethodCallHandler(new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall call, Result result) { if (call.method.equals("getBatteryLevel")) { int batteryLevel = getBatteryLevel(); result.success(batteryLevel); } else { result.notImplemented(); } } }); } private int getBatteryLevel() { // Logic for obtaining battery level } }
Conclusion:
Choosing between Embedding V1 and V2 boils down to your project needs. For basic Flutter integrations, Embedding V1 provides a simpler solution. However, if you require greater control, flexibility, or plan to manage multiple Flutter instances, Embedding V2 is the preferred option.