Behind the Development of A Simple poem: Quick Construction practice of Flutter Mobile App — State Management, Internationalization, Data Persistence, and Performance Optimization

Having covered the project structure, state management, and internationalization scenarios, this article continues with data persistence and rough performance tuning.

Data persistence

At present, flutter uses shared_preferences and SQFLite. One is the INI configuration file and the other is the SQLite database. I prefer to use the former for small applications. But Flutter does not yet have a good ORM framework, which makes it uncomfortable to write a lot of SQL statements.

So the following is a simple use of shared_preferences, detailed at pub.flutter-io.cn/packages/sh…

Add dependencies:

dependencies:
  shared_preferences: ^ 0.5.6
Copy the code

Here’s a simple example from the official website:

SharedPreferences prefs = await SharedPreferences.getInstance();
int counter = (prefs.getInt('counter')??0) + 1;
print('Pressed $counter times.');
await prefs.setInt('counter', counter);
Copy the code

Of course, it’s not enough to just copy the example from the official website, but what I want to talk about is data persistence, which is the method used in this project.

Remember the JSON Model module, which provides object serialization and deserialization for persistence. When saving data, convert the Model class to JSON data and store it in the SharedPreferences configuration, for example:

// Persist Profile information
static saveProfile() => _prefs.setString("profile", jsonEncode(profile.toJson()));
Copy the code

When the App starts, read the JSON data from SharedPreferences and create (deserialize) a Model object using the JSON constructor of the Model class, as shown in the following example:

_prefs = await SharedPreferences.getInstance();
var _profile = _prefs.getString("profile");
if(_profile ! =null) {
      try {
        profile = Profile.fromJson(jsonDecode(_profile));
        // Prevent null from being read out, which is used to upgrade existing profile data from version, if the installation is new
        profile.darkMode = profile.darkMode ?? false;
      } catch (e) {
        print(e); }}Copy the code

This completes the task of data persistence and is very simple.

The related configuration

Both flutter development and Android development are Google’s technology. As you know, Google servers are shielded and most of the Maven sources used by Gradle are inaccessible, so it is very slow to compile into Android Apk. We need to set up domestic sources.

Android /build.gradle, change the default Google () and jcenter() addresses to the following ones.

repositories {
     // google()
     // jcenter()
     maven { url 'https://maven.aliyun.com/repository/google' }
     maven { url 'https://maven.aliyun.com/repository/jcenter' }
     maven { url 'http://maven.aliyun.com/nexus/content/groups/public'}}Copy the code

To modify the android/gradle/wrapper/gradle – wrapper. The properties files.

#Wed Dec 11 15:10:31 HKT 2019distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME ZipStorePath = wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zipCopy the code

Change the last line to domestic server, such as: distributionUrl=https\://downloads.gradle-dn.com/distributions/gradle-5.1.1-all.zip, it is ok to change the domain name.

There is also a package publishing website in pub.dev, dart language, which is not accessible in China, but we have a domestic mirror: pub.flutter-io.cn/

Thanks to the efforts of the domestic open source community leaders!

For more information about the migration of Flutter to AndroidX, see: Development of Flutter: Migration of Flutter to AndroidX

The “Multithreading” of Flutter

Dart language is single-threaded, similar to JS. In flutter, UI and other operations are executed in the same thread. If there are time-consuming operations in the main thread, the interface becomes stuck. So if an operation can’t be completed within 1/60 of a second, it will affect the refresh of the interface and cause a noticeable lag.

So what’s the solution? Dart introduced something called Isolate, which is similar to threads but does not share memory with the main thread. If you want to share data, you must copy memory to pass parameters and get return values, which has many limitations compared to multithreading.

I won’t tell you more about the Isolate, please check the official documentation and the big guy’s blog for more details. Here is a record of my practice.

The overhead of switching between the main thread and the ISOLATE is very high, so in order to use multiple threads and improve performance, we need to reduce the creation of the ISOLATE. Therefore, we can use “thread pool” for load balancing, and define a LoadBalancer in the code to store our ISOLATE.

Future<LoadBalancer> loadBalancer = LoadBalancer.create(4, IsolateRunner.spawn);
Copy the code

Use loadbalancer to create reusable isolate:

final lb = awaitloadBalancer; Lb. Run (Isolate method, parameter);Copy the code

The ISOLATE method is a static method that accepts only one parameter. If you want to pass multiple parameters, you need to set your own protocol. You can write your own class, or you can pass dict or list. The result is returned as a value, and I usually return a dict(map).

Note: the ISOLATE cannot access the memory of the main thread. It is invalid to access variables from other parts of the ISOLATE. Use the method of passing parameters and getting returned values to exchange data.

There is a bug in flutter. The only way to do this is to use the official devTools “flutter. Dev /docs/testin…

To be continued

Unconsciously, I have written a lot more, and there are still some fragmentary content, as well as more performance optimization and App volume optimization content is being studied and summarized, the next article will continue to update ~

Welcome to communicate

Please leave a message in the background of wechat public account. I will reply to every message

  • Wechat official number: star painting master
  • Play code studio: live.bilibili.com/11883038
  • Zhihu: www.zhihu.com/people/deal…
  • Jane: www.jianshu.com/u/965b95853…