1. Why Flutter? (Characteristics of Flutter)

  • Performance: the realization of a self-drawing engine, maintain the consistency of different end UI, animation fluency
  • Ecology: According to Github, the number of active Flutter users is growing rapidly. Judging from Stackoverflow questions, the Flutter community is now huge.
  • Tech support: Google is promoting Flutter, many of the writers of Flutter are from the Chromium team, and it’s very active on Github.
  • Development efficiency: The thermal overload of Flutter helps developers quickly test, build UI, add features, and fix bugs faster. Hot reloading can be done on iOS and Android emulators or real phones at the millisecond level without loss of state.

2. A comparison of Flutter and RN.

1. Environment construction:

React Native:

NPM, Node, and React-native CLI configurations are required

Flutter:

Dart and the flutter plugin on Android Studio/VSCode are required.

2. Implementation principle:

React Native:

React Native will parse and render Native controls, such as labels corresponding to ViewGroup/UIView and labels corresponding to ScrollView/UIScrollView.The tag corresponds to ImageView/UIImageView etc.

Flutter:

The majority of widgets in Flutter are platform-independent. Developers build apps based on the Framework, which runs on Top of Engine and is adapted and supported across platforms by Engine. This cross-platform support process involves “datafitizing” widgets in the Flutter UI and drawing them directly onto the screen via Skia on the Engine

3. Language:

Both support variable definition via VAR, async/await syntactic sugar, and chained asynchronous processing such as Promise(Future)

JS is a dynamic language, while Dart is a strongly typed language of pseudo-dynamic languages. Both dynamic and non-dynamic languages have advantages and disadvantages. For example, JS is significantly easier to develop than Dart, and Dart is more robust than JS in terms of type safety and refactoring.

4. The graphic

3. Describe the difference and principle of Hot Reload, Hot Restart and Hot update.

The difference between

Hot restart is required for code that has changed the state, otherwise hot Reload is required

Hot Reload principle

Of the two compilation modes that Flutter provides, AOT is compiled statically, that is, into binary code that the device can execute directly. JIT is dynamic compilation, which compiles Dart code to Script Snapshot and requires the Dart VM to interpret execution at run time.

Hot overloading can only be used in Debug mode because the Flutter is JIT compiled in Debug mode (AOT compiled statically in Release mode). The JIT compiler compiles the Dart code into a Dart Kernel that can run on the Dart VM. The Dart Kernel can be updated dynamically, which enables real-time updates of the code.

In general, hot overloading can be completed in five steps: scanning for project changes, incremental compilation, push updates, code merging, and Widget reconstruction.

  1. Engineering changes. The hot-reload module scans files in the project for additions, deletes, or changes until it finds Dart code that has changed since the last compilation.
  2. Incremental compilation. The hot-reload module converts the changed Dart code into an incremental Dart Kernel file by compilation.
  3. Push updates. The hot-reload module sends the incremental Dart Kernel file to the Dart VM running on a mobile device via an HTTP port.
  4. Code merge. The Dart VM merges the received incremental Dart Kernel file with the original Dart Kernel file and then reloads the new Dart Kernel file.
  5. The Widget reconstruction. After confirming that the Dart VM resource has been successfully loaded, Flutter resets its UI thread to inform the Flutter Framework to rebuild the Widget.

Hot Reload scenarios are not supported

  • A compilation error occurred in the code;
  • Incompatible Widget state;
  • Changes to global variables and static properties;
  • Changes to the main method;
  • Changes in the initState method;
  • Enumeration and generic type changes

4. How does Flutter compile a Dart code that runs on Android and iOS? So the specific principle.

  • Skia rendering, cross-platform application layer rendering consistency
  • Method the Channel mechanism

To solve the problem of invoking the underlying capabilities of native systems and reusing the associated code base, Flutter provides a lightweight solution for developers, namely the Method Channel mechanism at the logical layer. Based on the method channel, we can expose the capabilities of native code to Dart in the form of interfaces that allow the Dart code to interact with native code as if it were calling a normal Dart API.

Flutter defines three different types of channels

  • BasicMessageChannel: Used to pass strings and semi-structured information.
  • MethodChannel: Used for method invocation.
  • EventChannel: Communication for Event streams.

Pay attention to

Method channels are non-thread-safe. Native code handling method call requests that involve asynchronous or off-main thread switching needs to make sure that the callback is executed in the UI thread of the native system (i.e., the main thread of Android and iOS), otherwise the application may experience strange bugs and even Crash.

5. Flutter does not have reflection. If you want to use reflection, how should you use it? Just to give you the general idea.

Using a Mirror

The main types of Mirror are as follows:

  • ClassMirror: Reflection type of the Dart class
  • InstanceMirror: Reflection type of the Dart instance
  • ClosureMirror: Reflection type of closure
  • DeclarationMirror: The reflection type of the class attribute
  • IsolateMirror: Reflection type of the Isolate
  • MethodMirror: The reflection type of the Dart method (including functions, constructors, and getters/setters)

6. Flutter does not use WebView and JS solutions. How to do hot update? Just to give you the general idea.

  • IOS is not currently supported and cannot be audited
  • Android, you can do this by replacing the so file

Tinker can be accessed for hot updates, and Bugly is used as the console of patch version to upload and distribute patches and count the number.

Android side Flutter hot update

7. How to make the package size of Flutter compilation APP smaller as possible?

1. Remove useless code and resources, compress images, and remove App Bundle from Android.

2. Dart compilation products were optimized accordingly

  • Dynamic delivery: Strip the Data segment and all non-essential products, and deliver them dynamically after packaging.
  • Built-in compression: sends packets dynamically in binary mode.

3. Optimization of Flutter engine compilation products

  • Main optimization ideas include upgrading Bulild Tools unified double compilation parameters,
  • Customizing builds to cut out certain useless functions within the engine.

4. Machine code instruction optimization

With machine code instructions reduced, Google responded that Dart and OC will be roughly equal in the future.

7. Our project was a comprehensive system of old projects, there are Android, iOS, and Web code, is a mix of development projects, now need to be migrated to Flutter, to join you to join the team to do the migration work of the project, how do you think the project engineering, container and architecture evolution should thinking from the dimension of what?

Use the Idle Fish team’s open source Flutter_Boost

  • Reusable general purpose hybrid solution
  • Support for more complex blending modes, such as home Tab support
  • Non-invasive solution: No longer depends on the solution to modify the Flutter
  • Support for common page life cycles
  • Unified and clear design concept

When a Native page container exists, FlutteBoost guarantees that there will always be a Widget as the contents of the container. Therefore, we should understand and perform routing operations based on the Native container. The Flutter Widget depends on the state of the Native page container.

When we talk about pages in the concept of FlutterBoost, we are referring to the Native container and its attached widgets. All page routing operations, opening and closing pages, are actually direct operations on the Native page container. No matter where the routing request comes from, it is eventually forwarded to Native to implement the routing operation. This is why you need to implement the Platform protocol when accessing FlutterBoost.

Use it to start Flutter hybrid development – FlutterBoost

8. APP startup speed and page loading speed have always been a concern of us, especially for mixed development projects. What is your opinion on Flutter rendering optimization?

1. Minimize the number of reconstructed components in Flutter

In real development, writing the entire page in a separate StatefulWidget would result in a lot of unnecessary UI rebuilding with each state update. Therefore, learn to dismantle components and use good design patterns and state management schemes to minimize the impact of state updates when they are needed.

2. Use const keywords when building components to inhibit widget rebuilding

The proper use of const keywords can greatly optimize application performance

There are also a few things to note when using const:

  • When const decorates the constructor of a class, it requires that all members of the class be final.

  • A const variable can only be initialized at definition time.

3. There may be an expensive method called saveLayer() behind some of the effects of Flutter implementation

Each of the following components triggers a saveLayer() call, which also causes performance loss:

  • ShaderMask
  • ColorFilter
  • Chip, when disabledColorAlpha! = 0xff, saveLayer() is called.
  • Text, if there is an overflowShader, may call saveLayer(),

4. The official also gave us some optimization points that need to be paid attention to:

Opacity widgets should not be used if Opacity widgets are not needed, since Opacity widgets use an off-screen buffer directly in the target component. For an example of applying transparency directly to an image, see Transparent Image, which is faster and performs better than using Opacity Widgets.

To fade in and out of an image, consider using the FadeInImage widget, which applies gradient opacity using the GPU’s fragment shader.

In many scenarios, it is unnecessary to use Opacity directly. For example, if you want to function on an image, you can use Opacity directly, or use Container: Container(color: color). Color. FromRGBO (255, 0, 0, 0.5))

Clipping will not invoke saveLayer () (unless explicitly use Clip. AntiAliasWithSaveLayer), so the operation is not so time-consuming Opacity, but still very time consuming, so please use caution.

5. Manage shader compilation garbage

Sometimes an animation in an application looks very slow on the first run, but works fine after a few runs, possibly due to a shader compilation mess.

On different platforms, you can use the following command to build an application using SkSL warm-up:

The android

Flutter build apk -- bundle-sksl-path flutter_01.sksl.jsonCopy the code

iOS

flutter build ios --bundle-sksl-path flutter_01.sksl.json
Copy the code

9. Talk about the memory reclamation management mechanism of Flutter and how you normally deal with the memory. How do you solve memory leaks and memory spills?

Dart’s garbage collection is generational: young and old

The GC connects to the Flutter Engine and notifies the engine when it detects that the application is idle and there is no user interaction. This gives the GC a window to collect without affecting performance.

  • The young generation

This stage is designed to remove ephemeral objects with short life spans, such as stateless widgets. Although it is blocking, it is much faster than mark-sweep in its old days, and when used in combination with scheduling, it barely affects the program’s performance.

To determine which objects are recyclable or not, the collector starts with root objects (such as stack variables) and examines the objects they reference. Then move the referenced object to the other half of the space. There it examines what the moving objects point to and moves the referenced objects. This is repeated until all live objects are moved to the other half of the space. Objects that are never referenced are reclaimed.

  • The old days (parallel marking and concurrent scanning)

When an object has been through a certain number of GCS and still exists, or it has a long life cycle (like Element and RenderObject, which are reusable, variable and expensive to create), put it in the old age region. The old days used tokenization to recycle objects.

This GC technique has two phases: the object graph is first traversed and the objects that are still in use are marked. During the second phase, the entire storage is scanned and any unmarked objects are reclaimed. Then clear all flags.

See the Dart Memory mechanism for details

10. A simpler question, how do you control the lifecycle of mixed projects (such as onCreate and onResume for Android) and route management?

The life cycle

Use system-provided callbacks

SystemChannels.lifecycle.setMessageHandler((msg) async { if (msg == AppLifecycleState.resumed.toString()) { } else if (msg == AppLifecycleState.inactive.toString()) { } else if (msg == AppLifecycleState.paused.toString()) { } else if (msg  == AppLifecycleState.detached.toString()) { } return ''; });Copy the code

Or use MethodChannel yourself on Android to notify the Flutter lifecycle of changes

Route Management:

When switching from a native page to a Flutter page, we usually encapsulate the Flutter container as a separate ViewController (iOS) or Activity (Android). After setting up the initial route to the page of the Flutter container (the root view), the native code can open the Flutter page just as it would open a normal native page.

If we want to jump from the Flutter page to the native page, we need to handle both opening the new native page and closing the page and reverting to the old native page. In both cases, we need to register the corresponding processing method using the method channel to open the new page and close the Flutter container in the native code host.

It is important to note that, unlike pure Flutter applications, native applications mix Flutter because it involves switching between native pages and Flutter pages. Therefore, there may be multiple Flutter containers in the navigation stack, i.e. multiple Flutter instances. The initial cost of a Flutter instance is very high. Every time a Flutter instance is started, a new rendering mechanism, the Flutter Engine, and the underlying Isolate, are created. However, the memory between these instances is not shared with each other, resulting in a large consumption of system resources.

To solve the problem of multiple Flutter instances in mixed engineering, the industry has two solutions:

Represented by Toutiao, the source code of Flutter Engine was modified to enable multiple Flutter engines corresponding to multiple FlutterView instances to share the underlying Isolate.

Shared FlutterView represented by Idle fish is the scheme of Flutter layer rendering content driven by native layer.

However, neither of these solutions is perfect at the moment. Therefore, before the official support of Flutter for multiple instances and single engine, Flutter should be used to develop some closed loop services to reduce the interaction between the native page and the Flutter page, and to avoid the situation that the Flutter page will jump to the native page and the native page will start a new Flutter instance. Ensure that there are no multiple Flutter container instances in the application.

11. What is the essential difference between Flutter for Web and Flutter Web introduced in Flutter1.9?

Web production quality support.

Focus specifically on three application scenarios:

  • Progressive Web Applications (PWA) that combine the reach of the Web with the capabilities of desktop applications.
  • A one-page application (SPA) that loads once and transfers data to and from Internet services.
  • Bring the existing Flutter mobile application to the Web to enable shared code for both experiences.

Over the past few months, as we prepare for a steady release of Web support, we’ve made a lot of progress in performance optimization, adding a new CanvasKit-powered rendering engine built by WebAssembly. Flutter Plasma is a demo built by community member Felix Blaschke to show how easy it is to build complex Web graphical experiences using Dart and Flutter that can also run locally on a desktop or mobile device.

12. How do you think Flutter Web should be improved? What content can be adapted for use in normal Web development. Tell me about your renovation plan.

  • Performance and compatibility issues
  • Too many plug-ins are not supported, ecology is not up
  • SEO optimization support is not good

13. Talk about how to create low-latency live video? Why is it used that way?

Use WebRTC

It uses UDP to stream media without the need to create discrete media segments, providing consistently low latency for all clients

WebRTC also provides a real-time two-way data channel that can be used to send and receive data streams. This two-way data technology opens up many interesting possibilities for how online streaming can now become an interactive experience.

The RTS service is deployed on the CDN node

RTS service is upgraded with service and node. Meanwhile, monitoring and targeted optimization are carried out for full-link live broadcast indicators. A series of underlying core technologies are optimized through intelligent scheduling system, network congestion, anti-weak network optimization and buffering strategy, so as to realize RTP over UDP to better combat public network packet loss. The stream quality received on the player is more stable than that of RTMP over TCP. In this way, the player can reduce the buffer, instead of setting the buffer for 6s as before to fight jitter, it only needs to be set for about 1 second, and the overall delay can be controlled within 1-1.5S.

How to build a low-delay live experience to make interaction more real-time?

14. Reference Links:

  • A comparative analysis of Flutter and React Native
  • How does the Hot Reload of Flutter work
  • How do YOU make android-ios platform-specific implementations compatible at the Dart layer?
  • Dart reflection at first glance
  • How to reduce the volume of a Flutter bag by nearly 50%
  • Optimization of Flutter Rendering Performance overview
  • Flutter 2.0 is a major update
  • How to implement a mix of Flutter and native development? Detailed description of the routing stack management for Flutter hybrid development