This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging

The background,

How to integrate Flutter as a library into a native project

Most of the projects are already existing and it would be impractical to rewrite the whole project with the new Flutter.

In this case, the Flutter can be integrated into an existing project as a module (source code) or a library (aar style). This module can then be imported into a native (Android or IOS) project to share the business logic written in the Dart language.

Two source code integration steps

1.1 Creating an Android project

Needless to say.

Add dependencies to Java8

Since the Flutter uses Java8 functionality, our native Android application needs to support Java8 as well.

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
Copy the code

1.3 Create the Flutter Module

1.4 Importing the Flutter Module

  1. Add the following code to settings.gradle
Properties properties = new Properties()
def dependFlutterSource = false
if (file('local.properties').canRead()) {
    properties.load(new FileInputStream(file('local.properties')))
    dependFlutterSource = properties.getProperty('dependFlutterSource'.'false').toBoolean()
}
setBinding(new Binding([gradle: this]))
def flutter_path = 'flutter_module/.android/include_flutter.groovy'
evaluate(new File(settingsDir,flutter_path))
Copy the code

DependFlutterSource is defined in local.properties under the project and will not be committed to Git. So the people on the project who are responsible for the Flutter development just need to set dependFlutterSource=true. If it is a native development,

1.5 Dependent flutter Module

Add a dependency on the flutter to build.gradle under the app

1.6 run

  1. Open the newly created Flutter_Module in the new Window

  1. If you configure the Activity path in the manifest file, you can normally jump to FlutterActivity.
<activity android:name="io.flutter.embedding.android.FlutterActivity"/>
Copy the code
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?).{... initView() }private fun initView(a) {
        findViewById<View>(R.id.btn2).setOnClickListener {
             startActivity(Intent(this, FlutterActivity::class.java))
        }
    }
}
Copy the code

Three AAR integration steps

3.1 You only need to modify step 1.5 above

. Properties properties =new Properties()
def dependFlutterSource = false
if (project.rootProject.file('local.properties').canRead()) {
    properties.load(new FileInputStream(project.rootProject.file('local.properties')))
    dependFlutterSource = properties.getProperty('dependFlutterSource'.'false').toBoolean()
}
dependencies{...if (dependFlutterSource) {
        api project(path: ':flutter')}else {
        api 'Your remote Flutter Module path'}}Copy the code