In fact, Flutter was introduced in 2017, but it was just a HelloWorld. On the one hand, Flutter was just the preview version at that time. On the other hand, ReactNative was very busy with ReactNative reconstruction project at that time. Missed the first echelon of the pit Flutter. At Google’s 2018IO conference, Flutter was once again the focus of cross-platform solutions, and ReactNative has been cooling off with the elimination of Airbnb. In fact, as I write this article, I have been in the dark again for quite some time, and basically all the features of Flutter have been covered. The Demo project has also written some, but the immediate reason WHY I am eager to write this article is because of Flutter’s ability to: Flutter can be imperceptively embedded into Android projects, whether from a developer or user perspective. You can even start with a view to get Flutter involved in your project, replace or develop a page or even a feature, and then you’ll love it. The urge to use it to refactor projects and develop new ones.

  • User: Millisecond load speed, whether view or page, is basically the same as native.
  • Development: only introduced as a module, code invasion is minimal, Android project and Flutter project are unrelated.

Note: the current date of flutter is July 29, 2018. The beta version of Flutter has not yet added this new feature. Use the flutter channel command to switch to the dev or master branch to use this feature.

Create an Android project that simulates your existing project

To make sure that The Android project and the Flutter project do not interfere with each other, the root directory of the Android project and the public directory of the Flutter project are not the Android project directory. The final directory structure should look like this

├── ├─ ├─ Garbage ├─ Garbage ├─ Garbage ├─ Garbage ├─ Garbage └Copy the code

So start by creating a new Android native project using AS in your project root directory, and check kotlin support for more comfort. When you’re done, you’ll have a structure that looks like this

├ ─ FlutterInAndroid? Your project root directory (anywhere you likeCopy the code

The FlutterInAndroid directory is a complete Android project

Module mode creates the Flutter project

Next use the Flutter command to create the Module project in your project root directory:

flutter create -t module my_flutter
Copy the code

When you’re done, you’ll have a structure that looks like this

├─ FlutterInAndroid ├─ my_flutterCopy the code

My_flutter is a Module project of Flutter for Android projects

Introduce dependencies into the Android project

In FlutterInAndroid the Android project setting. Gradle file additional flutter project with the introduction of your project directory/FlutterInAndroid/setting gradle

include ':app'
// Add the following configuration
setBinding(new Binding([gradle: this]))
evaluate(new File(
        settingsDir.parentFile,
        'my_flutter/.android/include_flutter.groovy'
))

Copy the code

In the build of the app. Gradle file to join the project depend on your project to the directory/FlutterInAndroid/app/build gradle

.dependencies{...// Add the following configuration
    implementation project(':flutter')}Copy the code

Open the FlutterInAndroid project with AS, rebuild the project, and successfully add Flutter to the Android project.

Create a View for Flutter in the Android project

Flutter provides two ways for Android projects to reference components. One is a View, and the other is a Fragment. Here we introduce FLutter in two ways, essentially introducing the layout as a view or using the FlutterView as the root view of the Activity.

Introduce the layout as a single view

val flutterView = Flutter.createView(this,lifecycle,"route1")
Copy the code

With this simple method we can create a view with a Flutter that takes three parameters. The first parameter is the Activity. The second parameter is a Lifecycle object. The third argument tells Flutter what view we want to create. This string argument is available in the Flutter project. Once you’ve created the FlutterView, you can add it to any layout you want as a general procedure.

Use the root View as the Activity

Create an empty Activity and use Flutter to create a View as the root View of the page:

class FlutterActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_flutter)
        val flutterView = Flutter.createView(this@FlutterActivity,lifecycle,"route1")
        val layout = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
        addContentView(flutterView, layout)
    }
}
Copy the code

Instead of using setContentView, we use the addContentView method, and here’s why: Although the FLutter loading is very fast, this process still exists. Before creating the FLutterView, we set up an R.layout.activity_flutter layout for the ContentView. This layout can be used as the interface to show the user before the FlutterView is loaded. Of course, in most cases, the user will not even know that the Flutter has been loaded, but we still need it because the loading speed of the Flutter in Debug mode is not very fast. This interface is useful for developers to look at, and without it there would be a black splash screen during Activity loading, which is not user-friendly.

Create different components for different routes in the Flutter project

Open the Flutter project with AndroidStudio in your project directory /my_flutter. This time AndroidStudio will recognize the Flutter project and load it as a Flutter project. Ignoring the.android and.ios folders, you will find that this FLutter project is not any different from the full FLutter project. You can still develop and debug a FLutter using the full FLutter project process. This is a very human design. Dart: Dart: View: View: View: View: View: View: View: View

void main() => runApp(new MyApp());
Copy the code

Our goal is to create different Flutter components to be used by the native project as views based on the native project’s calls. We can start with the main function. We can obtain the current routeName value from the window’s global variable. This value is the flag that was passed to the Flutter via the native project. With this flag, we can easily determine the different component creation of the Flutter:

import 'dart:ui';
import 'package:flutter/material.dart'; void main() => runApp(_widgetForRoute(window.defaultRouteName)); // Call Widget _widgetForRoute(String route) {switch (route) {case 'route1':
      returnSomeWidget(...) ;case 'route2':
      returnSomeOtherWidget(...) ; default:return Center(
        child: Text('Unknown route: $route', textDirection: TextDirection.ltr), ); }}Copy the code

Enable the Flutter module to support hot loading

Start the listening service in the Flutter directory and execute it in your project root directory /my_flutter

flutter attach
Copy the code

After execution, the listener service will wait and listen to the status of flutter in the debug application and then debug and run flutter in the AS of the FlutterInAndroid project in the normal way. The listener service of flutter will not start immediately after running the app in the real machine or emulator. A flutter is triggered when the view or Fragment of the flutter is activated. When a connection is established between the flutter listening service and app, the terminal will display the following output:

$ flutter attach -d W8
Waiting for a connection from Flutter on PLK UL00...
Done.
Syncing files to device PLK UL00...                          8.7s

🔥  To hot reload changes while running, press "r". To hot restart (and rebuild state), press "R". An Observatory debugger and profiler on PLK UL00 is available at: http://127.0.0.1:54218/ For a more detailed informationhelp message, press "h". To quit, press "q".

Copy the code

At this time, we modified the DART code file in the Flutter project, saved it, and then clicked the R key in the terminal for hot loading, and the R key for hot restart.

The signature is packaged

The introduction of the Flutter project has basically no impact on the construction of Android native projects. Packaging can be done as usual.

Comparison of Android projects in the Module project created by Flutter and Android projects in the pure Flutter project

The difference between Android project in Flutter’s Module project Android project in the Pure Flutter project
Folder name .android android
Include of the module The app and Flutter app
Explanation 1 App only provides a portal for activities. Flutter contains an interface for plugin extensions and native project calls The app contains entry activities and plug-in extensions
Instruction 2 App for Flutter development and debugging, Flutter as a module for Android native call App runs and packages as an Android project

For the convenience of description, we call the former module project and the latter the complete project.

Thus, although module project provides module named Flutter for native project invocation, app project is still retained. This greatly facilitates the Flutter engineer to independently develop the Flutter project without relying on any native invocation and start debugging by himself.


Refer to official wiki

Related articles Tencent NOW live team program Xianyu team program Meituan technical team program


More dry goods move to my personal blog www.nightfarmer.top/