Preface:
Hello, everyone! It has been a while since I updated my article to you. Recently, I have been studying the knowledge points of flutter and Android hybrid development. So just sort of summarize it and then share it with you. This article must be useful to Android Studio, so you need to change your IDE a little bit (but that’s not the point). So without further ado, let’s start.
The preparatory work
Need to install the flutter development environment: everyone can look at the previous tutorial: 1 win flutter system development environment installed tutorial: www.jianshu.com/p/152447bc8…
Install the Flutter development environment for MAC system
www.jianshu.com/p/bad2c35b4…
Effect:
The specific implementation
Create the Flutter_module project
-
1 Create it with Android Studio or command
-
2 Command Creation
flutter create -t module flutter_module
Copy the code
Note that android native projects need to be at the same directory level as Flutter_module
Step 2: Create an Android native project
This one is a little bit easier and I won’t say much more about it. Just follow the screenshots
Enter the Flutter_module in the Android project
- #####1 Add the following code to build. Gradle in the app directory of the native Android project
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Copy the code
We know that this is the configuration required to use Java 8. The purpose of this configuration is to resolve version-compatibility issues. Running the project without this configuration may cause an error: Invoked-customs are only supported starting with Android O (–min-api 26).
-
Gradle = setting.gradle = setting.gradle = setting.gradle = setting.gradle = setting.gradle
// add setBinding(new Binding([gradle: this])) evaluate(new File( settingsDir.parentFile, 'flutter_module/.android/include_flutter.groovy' ))Copy the code
Remember to change the name of your flutter module to sync · The project will be imported successfully
pit
Note here that when we are in sync we need to open the Flutter Module project and the native Android project at the same time otherwise it will failAfter sync we found that there was a library module named flutter in the directory structure of the native project. We need to add dependencies for this module to build. Gradle in the app directory
implementation project(':flutter')
Copy the code
In this way, we introduced the Flutter_module project into our Android project. Of course, flutter_Module can also be run separately
The Android native page opens the Flutter page
-
Add normal Flutter screen
Flutter provides FlutterActivity to display the Flutter experience in an Android app. Like any other Activity, FlutterActivity must register androidmanifest.xml in your account. Add the following XML to the file under the tag AndroidManifestxml application:
<activity android:name="io.flutter.embedding.android.FlutterActivity" android:theme="@style/Theme.Nativedemo" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|dens ity|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize" />Copy the code
-
2 start the activity
- 1 use FlutterActivity. CreateDefaultIntent
startActivity(FlutterActivity.createDefaultIntent(MainActivity.this));
Copy the code
This example assumes that your Dart entry point is called main() and the initial Flutter route is “/”. You cannot use an Intent that changes the Dart entry point, but you can use an Intent that changes the initial route. This method opens the default entry for the flutter and cannot customize the page of the flutter that you want to open
- 2 use FlutterActivity. WithNewEngine (.) initialRoute this way
startActivity(FlutterActivity.withNewEngine().initialRoute("route_page").build(MainActivity.this));
Copy the code
You can select the desired flutter page to open by passing the named route address configured in your Flutter Module project to initialRoute
- 3 Start FlutterActivity and send the value
We still through FlutterActivity. WithNewEngine () initialRoute in initialRoute life value
startActivity(FlutterActivity.withNewEngine().initialRoute("{name:'xq9527'}").build(MainActivity.this));
Copy the code
How does the Flutter Module receive data
import 'package:flutter/material.dart'; import 'dart:ui'; import 'my_home_page.dart'; import 'default_page.dart'; void main() => runApp( MyApp(initParams:window.defaultRouteName)); class MyApp extends StatelessWidget { String initParams = ''; MyApp({this.initParams}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), // routes: { // "/": (context) => DefaultPage(title: 'route_page'), // 'route_page':(context) => MyHomePage(title: 'router page'), // home: "/", home: MyHomePage(title: this.initParams,), ); }}Copy the code
In the flutter Module we need to pass window.defaultroutename our default route parameters to the myApp entry instantiated in the entry main method and then use the data native to our flutter
Use FlutterEngine package com.example.nativedemo; import android.app.Application; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterEngineCache; import io.flutter.embedding.engine.dart.DartExecutor; /*** ** founder xuqing * Created at 2021/4/20 * Public class MyApplication extends Application {public static final String ENGINEID = "my_engine_id"; @Override public void onCreate() { super.onCreate(); initFlutterEngine(); } private void initFlutterEngine(){ // Instantiate a FlutterEngine. FlutterEngine flutterEngine = new FlutterEngine(this); flutterEngine.getNavigationChannel().setInitialRoute("route_page"); Start executing Dart code to pre-warm the FlutterEngine. flutterEngine.getDartExecutor().executeDartEntrypoint( DartExecutor.DartEntrypoint.createDefault() ); // Cache the FlutterEngine to be used by FlutterActivity. FlutterEngineCache .getInstance() .put(ENGINEID, flutterEngine); }}Copy the code
use
FlutterActivity.withCachedEngine(MyApplication.ENGINEI).build(MainActivity.this);
Copy the code
Using FlutterFragment
-
Default boot mode
FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction(); FlutterFragment flutterFragment=null; FlutterFragment = flutterFragment. / / the default startup mode createDefault (); fragmentTransaction.add(R.id.main_framelayout, flutterFragment); fragmentTransaction.commit();Copy the code
-
Specify routing page
FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
FlutterFragment flutterFragment== FlutterFragment.withNewEngine()
.initialRoute("route_page")
.build();
fragmentTransaction.add(R.id.main_framelayout, flutterFragment);
fragmentTransaction.commit();
Copy the code
-
Using FlutterEngine
FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
FlutterFragment flutterFragment== FlutterFragment.withCachedEngine(MyApplication.ENGINEID)
.renderMode(RenderMode.surface)
.build();
fragmentTransaction.add(R.id.main_framelayout, flutterFragment);
fragmentTransaction.commit();
Copy the code
You can also use FlutterView, which I won’t go into here. If you are interested, you can check out the official document Add Flutter to Existing Apps
The final summary
Android’s native introduction of the Flutter Module is relatively simple to implement and the official documentation is detailed, but there are also some mistakes. I have mentioned this article in this issue. Finally, I hope my article can help you solve the problem, and I will contribute more useful code to share with you in the future. If you think the article is good, please pay attention and star. Thank you