The future of mobile app development: Flutter

Author: Eric Grandt

With the increasing complexity of systems and applications, "write once, run anywhere" has begun to become the ultimate goal of more and more development tools.

Based on this, Google launched Flutter, a mobile UI framework at the 2017 I/O Conference, which allows developers to quickly build high-quality native user interfaces on iOS and Android systems. At the same time, Apple also brought SwiftUI, a UI framework that can span Apple's major operating systems, to developers at WWDC 2019.

So under this trend, is a tool like Flutter really the future of a new generation of mobile development?

A few years ago, I dabbled in Android and iOS development, using Java and Objective-C. After spending about a month studying, I decided not to study in depth. I just can't find the state that goes deep into it.

But recently, I learned about Flutter and decided to try again in the direction of mobile application development. I immediately fell in love with it because it makes developing multi-platform applications fun. Since learning about it, I have used it to create an app and a library. Flutter seems to be a very promising step, and I want to explain several reasons why I believe this.

1. Technical support provided by Dart

Flutter uses the Dart language developed by Google. If you have used Java before, you will be familiar with Dart's syntax because they are very similar. But apart from the syntax, Dart is very different from Java.

I'm not going to discuss Dart in depth, so as not to digress, but I want to discuss its most useful features in my opinion. This function is asynchronous operation. Dart not only supports asynchronous operations, but also makes it very easy.

If you are doing IO or other time-consuming operations (such as querying the database), then you may use asynchronous operations in all Flutter applications. If there is no asynchronous operation, any time-consuming operation will cause the program to freeze until the operation is completed. To prevent this, Dart provides us with the async and await keywords to allow our program to continue execution while waiting for these longer operations to complete.

Let's look at a few examples: one with asynchronous operations and one without.

// Without asynchronous operations
import 'dart:async';

main() {
    longOperation();
    printSomething();
}

longOperation() {
    Duration delay = Duration(seconds: 3);
    Future.delayed(delay);
    print('Waited 3 seconds to print this and blocked execution.');
}

printSomething() {
    print('That sure took a while!');
}

Output t:

Waited 3 seconds to print this and blocked execution.
That sure took a while!

This is not ideal. No one wants to use an app that will get stuck when performing long operations. So let's modify it a bit and use the async and await keywords.

// With asynchronous operations
import 'dart:async';

main() {
    longOperation();
    printSomething();
}

Future<void> longOperation() async {
    var retVal = await runLongOperation();

    print(retVal);
}

const retString = 'Waited 3 seconds to return this without blocking execution.';
Duration delay = Duration(seconds: 3);

Future<String> runLongOperation() => Future.delayed(delay, () => retString);

printSomething() {
    print('I printed right away!');
}

And output again:

I printed right away!
Waited 3 seconds to return this without blocking execution.

With asynchronous operations, while we execute the code that takes a long time to complete, the execution of the rest of the code will not be hindered.

2. Write the code only once and run it on both Android and iOS

Considering the need to use different code bases for Android and iOS, developing mobile applications may take a lot of time. Unless you use an SDK like Flutter, you will have a code base that can adapt to both operating systems. Not only that, you can also run them completely natively. This means that things like browsing pages and navigation work perfectly with different operating systems.

In a nutshell, as long as you have a device or simulator running, Flutter can make the process of building and running your application for testing as simple as your fingers.

Three, UI development

UI development is almost one of the things I don't expect. I'm more of a back-end developer, so when it comes to things that rely heavily on it, I just want something simple. This is where Flutter shines in my eyes.

UI is created by combining different widgets and modifying them to suit your App appearance. You can almost completely control how these widgets are displayed, so you will always get what you want in the end. To lay out the UI, you can use widgets such as Row, Column, and Container. For content, there are such as Text and RaisedButton. These are just a few of the widgets provided by Flutter, and there are many other than these. Using these widgets, we can build a very simple UI:

@override
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text('Flutter App'),
            centerTitle: true,
            elevation: 0,
        ),
        body: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
                Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                        Container(
                            child: Text('Some text'),
                        ),
                        Container(
                            child: RaisedButton(
                                onPressed: () {
                                    // Do something on press
                                },
                                child: Text('PRESS ME'),
                            ),
                        ),
                    ],
                ),
            ],
        ),
    );
}

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-gcd7ipPE-1594103092983)(https://upload-images.jianshu.io/upload_images/22436740-905dc24af6484113?imageMogr2 /auto-orient/strip%7CimageView2/2/w/1240)]

Flutter is like a magician with a variety of props, allowing you to easily build App themes. You can manually change the font, color, and set everything one by one, but it will take too long. Instead, Flutter provides us with something called ThemeData, which allows us to set values ​​for colors, fonts, input fields, etc. This feature is excellent in maintaining the consistency of the appearance of the application.

theme: ThemeData(
    brightness: Brightness.dark,
    canvasColor: Colors.grey[900],
    primarySwatch: Colors.teal,
    primaryColor: Colors.teal[500],
    fontFamily: 'Helvetica',
    primaryTextTheme: Typography.whiteCupertino.copyWith(
        display4: TextStyle(
            color: Colors.white,
            fontSize: 36,
        ),
    ),
),

Using this ThemeData, we set the application color, font family and some text styles. Everything except the text style will be automatically applied to the entire app. The text style of each widget must be manually set one by one, but this is still very simple:

child: Text(
    'Some text',
    style: Theme.of(context).primaryTextTheme.display4,
),

To further improve efficiency, Flutter can hot reload the app, so you don't need to reopen it every time you change the UI. You can make changes now, save them, and see the effect of the changes in about a second.

Fourth, the library

Flutter provides many powerful features out of the box, but sometimes you need more features. Considering the large number of libraries available for Dart and Flutter, this is not a problem at all. Are you interested in advertising in your app? There are libraries for this. Want new widgets? There are libraries for this.

If you prefer to do it yourself, you can create your own library and share it with others in the community right away. Adding a library to the project is very simple and can be done by adding a line of code to the pubspec.yaml file. For example, if you want to add the sqflite library:

dependencies:
  flutter:
    sdk: flutter
  sqflite: ^1.0.0

After adding it to the file, run flutter packages get, and that's it. Various libraries make developing Flutter applications a breeze and save a lot of time in the development process.

Five, back-end development

Most apps now rely on some kind of data, and all this data needs to be stored somewhere so that it can be displayed and used later. Therefore, it is very important to keep this in mind when looking for new SDKs (such as Flutter) to create applications.

Again, Flutter App is made using Dart, and Dart is very good at back-end development. I talked about many simple and easy functions in this article, and the back-end development of Dart and Flutter is no exception. Whether it is for beginners or experts, creating data-driven apps is very simple, but this simplicity is not the same as quality.

You can use the library so that you can use the database of your choice. Using the sqflite library, we can start and run the SQLite database very quickly. Thanks to the one-piece model, we can access the database and query from almost anywhere without having to recreate an object every time.

class DBProvider {
    // Singleton
    DBProvider._();

    // Static object to provide us access from practically anywhere
    static final DBProvider db = DBProvider._();
    Database _database;

    Future<Database> get database async {
        if (_database != null) {
            return _database;
        }

        _database = await initDB();
        return _database;
    }

    initDB() async {
        // Retrieve your app's directory, then create a path to a database for your app.
        Directory documentsDir = await getApplicationDocumentsDirectory();
        String path = join(documentsDir.path, 'money_clip.db');

        return await openDatabase(path, version: 1, onOpen: (db) async {
            // Do something when the database is opened
        }, onCreate: (Database db, int version) async {
            // Do something, such as creating tables, when the database is first created.
            // If the database already exists, this will not be called.
        }
    }
}

After retrieving data from the database, you can use a model to transform it into objects. Or, if you want to store the object in a database, you can use the same model to convert it to JSON.

class User {
    int id;
    String name;

    User({
        this.id,
        this.name,
    });

    factory User.fromJson(Map<String, dynamic> json) => new User(
        id: json['id'],
        name: json['name'],
    );

    Map<String, dynamic> toJson() => {
        'id': id,
        'name': name,
    };
}

If there is no way to show it to the user, the data is not so useful. This is when Flutter comes on stage with widgets such as FutureBuilder or StreamBuilder. If you are interested in using Flutter, SQLite and other technologies to create data-driven apps for a deeper understanding, I suggest you check this article:

Six, some final thoughts

With Flutter, there are almost endless possibilities, so even huge apps can be created easily. If you are doing mobile app development and have not tried Flutter, I strongly recommend you to try it, because I believe you will love it too. After using Flutter for a few months, I think it can be said that this is the future of mobile development. If the future cannot be counted, this is definitely a step in the right direction.

Last

Here I also share an Android learning PDF+architecture video+interview document+source notes , advanced architecture technology advanced mind map, Android development interview special materials, advanced advanced architecture materials collected and organized by several big guys .

These are fine materials that I will read again and again in my spare time. Can effectively help everyone master knowledge and understand principles. Of course, you can also use it to check for omissions and improve your competitiveness.

If you need it, you can  get it here

If you like this article, you might as well give me a thumbs-up, leave a message in the comment area or forward and support it~

Guess you like

Origin blog.csdn.net/River_ly/article/details/107180728