In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "Flutter mixed Development Analysis". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Brief introduction of mixed development
It is easy and comfortable to use Flutter to develop App from scratch, but for some mature products, it is unrealistic to completely abandon the historical precipitation of the original App and turn to Flutter. Therefore, we use Flutter to unify the Android and iOS technology stack, regard it as the expansion ability of the existing native App, and improve the development efficiency of the mobile terminal through orderly promotion.
Currently, there are two main ways to embed some Flutter pages in existing native App. One is to take the native project as a sub-project of the Flutter project, which is uniformly managed by Flutter, which is called unified management mode. The other is to take the Flutter project as a sub-module of the native project to maintain the original original project management mode, which is called the three-terminal separation mode.
In the early days of the emergence of the Flutter framework, due to the official mixing methods and limited materials, the early domestic teams that used Flutter for mixed development mostly used the unified management model. However, with the deepening of business iteration, the disadvantages of the unified management model are also exposed, not only the three ends (Android, iOS and Flutter) code coupling is serious, the related tool chain time-consuming also increases greatly, resulting in the reduction of development efficiency. Therefore, the subsequent teams that use Flutter for mixed development mostly use the pattern of three-terminal code separation for dependency governance, and finally achieve lightweight access to Flutter projects.
In addition to lightweight access, the three-terminal code separation mode can also use the Flutter module as a sub-module of the native project, so as to quickly access the Flutter module and reduce the transformation cost of the native project. After completing the access to the Flutter module, the Flutter project can be developed using Android Studio, and the Dart code and native code can be developed and debugged without opening the native project.
The key to using the three-terminal separation mode for Flutter mixed development is to extract the Flutter project and manage the construction products of different platforms according to the standard component form, that is, Android uses aar and iOS uses pod. In other words, the mixed solution of Flutter is to package Flutter modules into aar or pod libraries, and then introduce Flutter modules into native projects like other third-party native component libraries.
Flutter module
By default, the newly created Flutter project contains the Flutter directory and the native project directory. In this case, the native project relies on the libraries and resources of the Flutter project and cannot be built and run independently from the Flutter project. In mixed development, the dependence of native engineering on Flutter is mainly divided into two parts. One is the library and engine of Flutter, which mainly contains the Framework library and engine library of Flutter; the other is the Flutter module project, that is, the Flutter function module in Flutter mixed development, which mainly includes the implementation of Dart code under the lib directory of Flutter project. For native projects, integrating Flutter is simply a matter of creating a Flutter module in the sibling directory, and then building the respective Flutter dependent libraries of iOS and Android. Next, we just need to execute the build module command provided by Flutter to create the Flutter module under the sibling directory of the native project, as shown below.
Flutter create-t module flutter_library
Where flutter_library is the name of the Flutter module. After executing the above command, a flutter_library module project is generated in the sibling directory of the native project. The Flutter module is also a Flutter project. Open it using Android Studio and its directory is shown in the following figure.
As you can see, compared with ordinary Flutter projects, Flutter module projects also have embedded Android projects and iOS projects, but by default, Android projects and iOS projects are hidden. Therefore, for Flutter module projects, Android Studio can also be used for development and debugging like ordinary projects. At the same time, compared with the ordinary Flutter project, there is an additional Flutter directory under the Android project directory of the Flutter module project, and the build.gradle configuration in this directory is the packaging configuration when we build aar. Similarly, you will find a Flutter directory under the iOS project directory of the Flutter module project, which is why the Flutter module project can not only use Android Studio for development and debugging, but also package and build aar or pod like the ordinary Flutter project.
Android integrated Flutter
Integrating Flutter in native Android engineering, the dependence of native engineering on Flutter mainly includes two parts, namely, Flutter library and engine, and Flutter engineering construction products.
Flutter library and engine: contains icudtl.dat, libFlutter.so, and some class files, which will eventually be packaged into Flutter.jar. Flutter engineering products: including application data segment isolate_snapshot_data, application instruction segment isolate_snapshot_instr, virtual machine data segment vm_snapshot_data, virtual machine instruction segment vm_snapshot_instr and resource file flutter_assets.
In the same way as the native Android project integrates other plug-in libraries, introducing the Flutter module into the native Android project requires the following code to be added to settings.gradle first.
SetBinding (new Binding ([gradle: this])) evaluate (new File (settingsDir.parentFile, 'flutter_library/.android/include_flutter.groovy'))
Where flutter_library is the Flutter module we created. Then, add the following dependencies to the build.gradle file in the app directory of the native Android project.
Dependencies {implementation project (": flutter")}
Then compile and run the native Android project, and if there are no errors, the integration of the Flutter module is successful. It is important to note that since the minimum version supported by Flutter is 16, you need to change the minSdkVersion of the Android project to 16. If there is a "package android.support.annotation does not exist" error, you need to use the following command to create the Flutter module, because the latest version of Android uses androidx to manage packages by default.
Flutter create-- androidx-t module flutter_library
For Android native projects, if you haven't upgraded to androidx, you can right-click the native Android project, and then select [Refactor] → [Migrate to Androidx] to upgrade the Android project to androidx package management. After successfully adding Flutter module dependencies to the native Android project, open the native Android project and add the following code to the entry MainActivity file of the application.
Public class MainActivity extends AppCompatActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); View flutterView = Flutter.createView (this, getLifecycle (), "route1"); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); addContentView (flutterView, layoutParams);}}
With the createView () method provided by Flutter, you can build the Flutter page into a view that Android can recognize, and then add that view to the parent window using the addContentView () method provided by Android. Rerun the native Android project, and the final result is shown in the following figure.
If the MainActivity of the native Android loads a FrameLayout, then the load only needs to build the Flutter page into a Fragment, as shown below.
Public class MainActivity extends AppCompatActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); FragmentTransaction ft= getSupportFragmentManager () .beginTransaction (); ft.replace (R.id.fragment_container, Flutter.createFragment ("Hello Flutter")); ft.commit ();}}
In addition to integration using Flutter modules, you can package Flutter modules into aar and then add dependencies. Execute the aar package build command under the flutter_library root directory to extract Flutter dependencies, as shown below.
Flutter build apk-debug
The purpose of this command is to compile the Flutter library, engine and engineering products into an aar package. The AAR package compiled by the above command is the debug version. If you need to build the release version, you only need to replace the debug in the command with release. The packaged flutter-debug.aar is located in the .Android / Flutter/build/outputs/aar/ directory. You can copy it to the app/libs directory of the native Android project, and then add the dependency to it in the packaging configuration build.gradle in the app directory of the native Android project, as shown below.
Dependencies {implementation (name: 'flutter-debug', ext:' aar')}
Then recompile the project, and if there is no error prompt, the Flutter module has been successfully integrated into the Android native project.
IOS integrated Flutter
The dependence of native iOS projects on Flutter includes Flutter libraries and engines, as well as Flutter project compilation products. Among them, Flutter libraries and engines refer to Flutter.framework and so on, and Flutter project compilation products refer to App.framework and so on. To integrate Flutter in a native iOS project, you need to configure CocoaPods,CocoaPods, a class library management tool for iOS, to manage third-party open source libraries. Execute the pod init command in the native iOS project to create a Podfile file, and then add the Flutter module dependency to the Podfile file, as shown below.
Flutter_application_path ='.. / flutter_ library/load File.join (flutter_application_path, '.ios', 'Flutter',' podhelper.rb') target 'iOSDemo' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! Install_all_flutter_pods (flutter_application_path) # Pods for iOSDemo … / / omit other scripts end'
Then, close the native iOS project and execute the pod install command in the root directory of the native iOS project to install the required dependency packages. After the installation is complete, open the iOSDemo.xcworkspace native project using Xcode.
By default, Flutter does not support Bitcode, Bitcode is the intermediate code of an iOS compiler, and integrating Flutter in a native iOS project requires Bitcode to be disabled. In Xcode, select [TAGETS] → [Build Setttings] → [Build Options] → [Enable Bitcode] to disable Bitcode, as shown in the following figure.
If you are using an earlier version of Flutter, you also need to add build phase to support building Dart code. Select [TAGGETS] → [Build Settings] → [Enable Phases], then click the plus sign in the upper left corner to create a new "New Run Script Phase" and add the following script code.
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
However, the latest version of Flutter no longer needs to add scripts. Rerun the native iOS project, and if there are no errors, iOS has successfully integrated the Flutter module.
In addition to using the Flutter module approach, you can package the Flutter module into a dynamic library that you can rely on, and then use CocoaPods to add the dynamic library. First, execute the package build command under the flutter_library root directory to generate the framework dynamic library, as shown below.
Flutter build ios-debug
The above command is to compile the Flutter project into Flutter.framework and App.framework dynamic libraries. If you want to generate a release version, you just need to replace the debug in the command with release.
Then, create a directory called FlutterEngine under the root of the native iOS project, and copy the two generated framework dynamic library files into it. However, iOS takes one more step than Android to generate modular artifacts because the libraries compiled by the Flutter project need to be manually encapsulated into a pod. First, create a FlutterEngine.podspec under the directory flutter_ library, and then add the following script code.
Pod::Spec.new do | s | s.name = 'FlutterEngine' s.version =' 0.1.0 's.summary =' FlutterEngine' s.description = 'LICENSE'} s.author = {' xzh' = > '1044817967 roomqq.com'} s.source = {: git = > ",: tag = >" # {s.version} "} s.ios.deployment_target =' 9.0' s.ios.vendored_frameworks = 'App.framework',' Flutter.framework'end
Then, execute the pod lib lint command to pull the components required by the Flutter module. Next, add the generated library to the Podfile file of the native iOS project.
Target 'iOSDemo' do pod' FlutterEngine',: path = >'. / 'end
Re-execute the pod install command to install the dependent library, and the native iOS project integration Flutter module is completed. Next, open the ViewController.m file using Xcode and add the following code.
# import "ViewController.h" # import # import @ interface ViewController () @ end@implementation ViewController- (void) viewDidLoad {[super viewDidLoad]; UIButton * button = [[UIButton alloc] init]; [button setTitle:@ "load Flutter module" forState:UIControlStateNormal]; button.backgroundColor= [UIColor redColor]; button.frame = CGRectMake (50,50,200,100); [button setTitleColor: [UIColor redColor] forState:UIControlStateHighlighted]; [button addTarget:self action:@selector (buttonPrint) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button] }-(void) buttonPrint {FlutterViewController * flutterVC = [[FlutterViewController alloc] init]; [flutterVC setInitialRoute:@ "defaultRoute"]; [self presentViewController:flutterVC animated:true completion:nil];} @ end
In the above code, we created a button in the native iOS that, when clicked, jumps to the Flutter page, as shown in the figure below.
By default, Flutter provides two invocation methods, FlutterViewController and FlutterEngine. For FlutterViewController, opening the ViewController.m file, adding a method to load the flutter page and adding a button appears to be called.
Flutter module debugging
As we all know, one of the advantages of Flutter is the use of hot and overload features in the development process to achieve fast debugging. By default, the hot overload function is invalid after the Flutter module is integrated into the native project, and you need to rerun the native project to see the effect. As a result, the hot overload advantage of Flutter development is lost, and development efficiency is reduced.
So, can you turn on the hot overload of Flutter in a hybrid project? The answer is yes, you only need to go through the following steps to turn on the hot overload function. First of all, close the native application, which refers to the process of shutting down the application, rather than simply exiting the application. Enter the flutter attach command in the root directory of the Flutter module, and then open the native application again, and you will see a prompt for a successful connection, as shown in the following figure.
If multiple devices are connected at the same time, you can use the flutter attach-d command to specify which devices are connected. Next, just press the r key to perform the hot reload, press the R key to perform the hot restart, and press the d key to disconnect.
In the Flutter project, we can directly click the debug button to debug the code, but in the mixed project, clicking the debug button directly does not work. At this point, you can use the flutter attach button provided by Android Studio to establish a connection with the flutter module and debug the code of the flutter module, as shown in the following figure.
The above only completed the introduction of the Flutter module in the native project, and the specific development will also encounter communication problems with the Flutter module, routing management problems, and packaging and so on.
This is the end of "Flutter mixed Development Analysis". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.