This is an excellent article translated by Lao Meng. This article has 3.6k likes. Join old Meng Flutter communication Group (WX: Laomengit).
Original address: medium.com/free-code-c…
A few years ago, I dabbled in Android and iOS development using Java and Objective-C, and after about a month of experimenting with them, I decided to move on.
But recently, I learned about Flutter and decided to develop the mobile app again. I immediately fell in love with it because it made developing multi-platform applications so much fun. Since then, I’ve created an application and a library to use it. Flutter seems to be a very promising step forward and I want to explain some different reasons why I believe in it.
Supported by Dart
Flutter uses the Dart language developed by Google. If you have worked with Java before, you will be familiar with Dart’s syntax because it is very similar. Dart is a completely different language except for its syntax.
I won’t get into Dart because it’s a little out of scope, but I want to discuss one of the features THAT I think is most useful. This feature supports asynchronous operations. Dart not only supports it, but makes it surprisingly easy.
If you are performing IO or other time-consuming operations (such as querying a database), you will most likely use this feature in all Flutter applications. There are no asynchronous operations, and any time-consuming operations cause the program to freeze until complete. To prevent this, Dart provides us with async and await keywords that allow our program to continue executing while we wait for these longer operations to complete.
Let’s look at a few examples: one with no asynchronous operation and one with asynchronous operation.
// 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! '); }Copy the code
Output t:
Waited 3 seconds to print this and blocked execution.
That sure took a while!
Copy the code
This is not ideal. No one wants to use an application that freezes during runtime operations. So let’s make some changes to it 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! '); }Copy the code
Output again:
I printed right away!
Waited 3 seconds to return this without blocking execution.
Copy the code
Thanks to asynchronous operations, we can execute code that takes a while to complete without blocking the execution of the rest of the code.
Write once and run on Android and iOS
Considering that you need to use different code bases for Android and iOS, developing mobile applications can take a lot of time. Unless you use an SDK like Flutter, you only have one code base that allows you to build applications for both operating systems. Not only that, but you can run them completely locally. This means features such as scrolling and navigation, just as they are for the operating system in use.
In keeping with the theme of simplicity, Flutter makes creating and running applications as easy as clicking a button, as long as you’re running a device or emulator.
UI development
UI development is one of those things I almost never look forward to. I’m more of a back-end developer, so I need something simple when dealing with something that relies heavily on it. This is where Flutter shines in my eyes.
Create the UI by combining different widgets and modifying them to fit the look and feel of your application. You have almost complete control over how these widgets are displayed, so you always get the exact information you need. To lay out the UI, you need to use widgets, such as rows, columns, and containers. For content, you have widgets such as Text and RaisedButton. These are just a few of the widgets that Flutter offers, and there are many more. 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'),
),
),
],
),
],
),
);
}
Copy the code
Flutter can easily set the theme theme. You could manually change the fonts, colors, and then go through everything, but that would take too long. Instead, Flutter provides us with something called ThemeData, which allows us to set values for colors, fonts, input fields, and so on. This feature is ideal for keeping the look and feel of your application consistent.
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,
),
),
),
Copy the code
With ThemeData, we can set the color, font family, and certain text styles of our application. With the exception of text styles, everything is automatically applied across the entire application. You must manually set the text style for each text widget, but it’s still simple:
child: Text(
'Some text',
style: Theme.of(context).primaryTextTheme.display4,
),
Copy the code
To improve efficiency, Flutter can thermally reload applications, so you don’t have to restart it every time you change the UI. Now you can make changes, save them, and see the changes in a second or so.
library
Flutter offers many great features right out of the box, but sometimes you need more than it provides. Given the number of libraries available for Dart and Flutter, this isn’t a problem at all. Interested in placing ads in your app? There’s a library. Need a new widget? Have a library.
If you prefer to do it yourself, create your own library and share it with the rest of the community immediately. Adding the library to your project is simple and can be done by adding a line to the pubspec.yaml file. For example, if you want to add the SQflite library:
Dependencies: flutter: SDK: flutter: sqfliteCopy the code
After adding it to the file, run the FLUTTER package GET and you can get started. Libraries make developing Flutter applications a breeze and save a lot of time in the development process.
The backend development
Most applications today rely on some kind of data that needs to be stored somewhere for later display and use. It is therefore important to keep this in mind when creating applications using new SDKS, such as Flutter.
Again, the Flutter application is built using Dart, which is great for back-end development. I’ve talked a lot about simplicity in this article, and back-end development with Dart and Flutter is no exception. Creating data-driven applications is extremely simple for beginners and experts alike, but this simplicity is by no means the same as a lack of quality.
To link this to the previous section, you can use libraries, so you can use a database of your choice. Using the SQflite library, we can get the SQLite database up and running fairly quickly. And thanks to singletons, we can access the database and query it almost anywhere without having to recreate the object each 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. } } }Copy the code
After you retrieve the data from the database, you can use the model to transform it into objects. Or, if you want to store an 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,
};
}
Copy the code
The data is not that useful if it is not presented to the user. This is where Flutter comes with widgets such as FutureBuilder or StreamBuilder. If you want to learn more about how to create data-driven applications using Flutter, SQLite, and other technologies, I suggest you read the article I wrote:
How to use Streams, BLoC and SQLite in Flutter
Final thoughts
With Flutter, the possibilities are almost limitless, so it is even easy to create super-scalable applications. If you develop mobile applications and have not yet tried Flutter, I strongly recommend that you do so, as I am sure you will fall in love with Flutter as well. After using Flutter for a few months, I think it’s safe to say that this is the future of mobile development. If not, it’s certainly a step in the right direction.
communication
Old Meng Flutter blog address (330 controls usage) : laomengit.com