Flutter's first exploration of native mixed development

Reprint please indicate the source: https://juejin.cn/post/7246778558248058938

This article is from Ronghua Xiehou's blog

0. write in front

Nowadays, cross-platform technology is proposed and applied by more and more developers. From the earliest Java to later RN, Weex, and now Compose and Flutter, large front-ends have become a trend. In order to save costs, many companies, including some Dachang has already used Flutter technology on Android and iOS platforms, and the effect is not bad, close to the original, but there will still be some lagging problems. Fortunately, Flutter is still constantly optimizing and updating, and I hope it will get better and better.

It has been 6 years since Flutter was released in 2017. If you create a Flutter project now, you will find that it supports six major operating system platforms: Android, iOS, Linux, MacOS, Web, and Windows. I used to write Some small tools that run on Windows are written in java, not only the complex interface is not good-looking, but I tried it with Flutter, and it seems that I have discovered a new world. It runs very smoothly on PC, and directly supports running on other platforms, which feels very good. , which also makes me look forward to the future development of Flutter.

There are two ways to develop Flutter, one is pure Flutter development, and the other is Flutter+native development. As mentioned above, Flutter runs very smoothly on the PC, which may be due to the relatively high configuration of the PC, but in the client However, the running effect on it is not satisfactory, the startup is a bit slow, some complex lists are a bit stuck, and some underlying function APIs are not supported, which requires the intervention of native development. A small part of native + most Flutter development may be the mainstream one in the future. way of development.

This article mainly talks about some steps of mixed development with Flutter on the Android platform. Let's take a look.

1. Prepare

1.1 First post the development environment I use:

  • Operating system: Windows 10

  • IDE:Android Studio Flamingo

  • Android SDK:33

  • Gradle:8.0.2

  • JDK:17.0.7

  • Flutter:3.10.4

1.2 Download the Flutter SDK

Download address: docs.flutter.dev/get-started…

It is a compressed package, unzip it to the directory where you store the development environment, then open File->Settings->Languages&Frameworks in AS, and configure the path of the SDK in it.

1.3 Configure environment variables

Like Jdk, for the convenience of use, you also need to configure the environment variables, set->about->advanced system settings->environment variables, find the user variables, add a new path in the path flutter SDK path\bin, if there is If it is worth, don't forget to add an English semicolon in front to separate it.

1.4 Detect flutter status

In order to verify whether Flutter is successfully installed, open the cmd command line and enter flutter doctor for detection:

flutter doctor

If the above prompt appears, it is because of an Android certificate problem, and then enter flutter doctor --android-licenses to fix it:

Does not support Jdk 1.8 version

Such an error may occur. This is because the JDK version is a bit low. Most of them still use the 1.8 version. After installing and configuring JDK 17, you can run the flutter doctor again:

flutter doctor via

1.5 Install the Flutter plugin

Open File->Settings->Plugins in AS and install the following two plugins:

plug-in

At this point, all the preparatory work is completed, and then create a project.

2. Create a project

First create a standard Android project, on this basis, open File->New->New Flutter Project to create a Flutter Module:

Create a Flutter Module

Note that Project location should select your current project directory, Project types select Module, and then CREATE, look at the created directory structure:

Directory Structure

3. Project Flutter configuration

Open the settings.gradle configuration file in the project root directory and add the following configuration:

// Flutter配置
setBinding(new Binding([gradle: this]))
evaluate(new File(
        settingsDir,
        'flutter_lib/.android/include_flutter.groovy'
))
include ':flutter_lib'


Then modify dependencyResolutionManagement, change FAIL_ON_PROJECT_REPOS to PREFER_SETTINGS, and add flutter's maven warehouse address:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
    repositories {
        google()
        mavenCentral()
        maven {
            allowInsecureProtocol = true
            url "http://download.flutter.io"
        }
    }
}

Find flutter_lib->.android->Flutter->build.gradle, and add namespace to the android attribute. This is a new feature of Gradle 8.0:

android {
    namespace 'com.example.flutter_lib'
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion
    ...
}

Find the build.gradle of the main app, and refer to the flutter module in dependencies. Note that the module name is flutter. No matter what the name of the Moudle you created, the name here is flutter:

dependencies {
    ...
    implementation project(':flutter')
}

4. Get started

In the manifest file, add the following activity tag. Note that this activity comes with the SDK and does not need to be created manually:

<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" />
</application>

Write a jump method in MainActivity for testing:

val intent = FlutterActivity
    .withNewEngine()
    .initialRoute("home")
    .build(this)
startActivity(intent)

Look at the effect:

jump effect

It can be seen that after clicking the jump button, there is an obvious pause, which is caused by the slow initialization of the Flutter engine, so try to initialize the engine in advance, and initialize the engine in the Application:

class App : Application() {

    override fun onCreate() {
        super.onCreate()
        // 创建 Flutter 引擎
        val flutterEngine = FlutterEngine(this)
        // 指定要跳转的flutter页面
        flutterEngine.navigationChannel.setInitialRoute("main")
        flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())
        // 这里做一个缓存,可以在适当的时候执行它,例如app里,在跳转前执行预加载
        val flutterEngineCache = FlutterEngineCache.getInstance()
        flutterEngineCache.put("default_engine_id", flutterEngine)
    }
}

Then use the engine that has been created in advance to jump again:

val intent = FlutterActivity
    .withCachedEngine("default_engine_id")
    .build(this)
startActivity(intent)

Look at the effect, it is very silky:

Jump effect after optimization

at last

If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.

If you have no direction, here is a set of "Advanced Notes on Eight Android Modules" written by a senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently master various knowledge points of Android development.
insert image description here
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.

Full set of video materials:

1. Interview collection

insert image description here
2. Source code analysis collection
insert image description here

3. The collection of open source frameworks
insert image description here
welcomes everyone to support with one click and three links. If you need the information in the article, just click the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓

Guess you like

Origin blog.csdn.net/Eqiqi/article/details/131387049