This article was first published on wechat official account “Liu Wangshu”
preface
Dart is the language specified by the Flutter SDK, so Dart must be mastered to learn Flutter. There could be a book to be written about Dart, but here’s a quick introduction to the essence of Dart. This article will try not to cover anything similar to the Java language.
1. Build the Dart development environment
Learning the Dart syntax is best done with an editor, and IntelliJ IDEA is recommended. Download the Dart SDK at www.gekorm.com/dart-window… Open IntelliJ IDEA, click File >Settings >plugins, search for the Dart in the plugins search box, and then restart IntelliJ IDEA. Click File–>New Project–>Dart to configure the Dart SDK as shown in the following figure.
void main(a) {
print("Hello World");
}
Copy the code
Dart: Dart: dart: dart: dart: dart: dart: dart: dart: dart: dart: dart: dart
2. Summary of the Dart
Dart is a Computer programming language developed by Google that debuted in October 2011. The latest version is Dart2. Dart was born out of frustration with JavaScript by Google engineers, and was initially embraced by some front-end developers. But as JavaScript catches on with NodeJS, Dart gets lost in front end, back end, and mobile end, and Dart is strong on its own, but unlucky. Dart is back on the scene. Angular offers Dart as the official development language for Fuchsia, and Dart as the development language for Flutter, a mobile UI framework. Dart normally runs on DartVM, but it can also compile native code to run on hardware under certain circumstances. For example, Flutter compiles code to platform-native code to improve performance.
3. Dart features and key concepts
Dart has the following features:
- Dart is compiled Ahead Of Time (AOT) into fast, predictable native code, which makes Flutter almost entirely possible to write using Dart. It can also be compiled using Just In Time (JIT).
- Easy to portable, Dart compiles to ARM and X86 code so it can run on Android, iOS, and elsewhere.
- Easy to get started, Dart absorbs high-level language features, and if you’re already familiar with C++, C, or Java, you can develop with Dart in just a few days.
- Easy to read. Dart enables Flutter to eliminate the need for a separate declarative layout language (XML or JSX), or a separate visual interface builder, because Dart’s declarative programming layout is easy to read.
- Avoiding preemptive scheduling, Dart can do object allocation and garbage collection without locking. Like JavaScript, Dart avoids preemptive scheduling and shared memory, so locks are not required.
Key Dart concepts include the following:
- In Dart, everything is an Object, each Object is an instance of a class, and all objects inherit from Object.
- Dart parses all code before it runs, specifying data types and compile-time constants to make code run faster.
- Unlike Java, Dart does not have the keywords public, protected, or private. If an identifier is underlined
_
To begin with, both it and its libraries are private. - Dart supports top-level functions such as main(), static and instance methods of classes or objects, and can create functions inside functions.
- Dart supports top-level variables as well as static variables for classes or objects and instance variables, sometimes called fields or properties.
- Dart supports generic types such as
List<int>
(integer list) orList<dynamic>
(List of objects of any type). - The Dart tool can report two types of problems: warnings and errors. Warnings merely indicate that the code may not work properly, but do not prevent the program from executing. Errors can be compile-time or run-time. Compile-time errors prevent code execution; Runtime errors cause code execution to report exceptions.
4. Dart
The keyword | |||
---|---|---|---|
abstract | dynamic | implements | show |
as | else | import | static |
assert | enum | in | super |
async | export | interface | switch |
await | extends | is | sync |
break | external | library | this |
case | factory | factory | factory |
catch | false | new | true |
class | class | null | try |
const | finally | on | typedef |
continue | for | operator | var |
covariant | Function | part | part |
default | get | rethrow | while |
deferred | hide | return | with |
do | if | set | set |
5. The variable
Variable declarations use the var keyword. The initial value of uninitialized variables is NULL, even for numeric variables.
var name = 'liuwangshu';
Copy the code
The name variable, whose type is inferred to be String, can also display declarations:
String name = 'liuwangshu' ;
Copy the code
If the Object is not limited to a single type, you can specify Object or Dynamic.
Object name = 'liuwangshu' ;
Copy the code
If the defined variable does not change, you can use final or const instead of var. Final variables can only be set once.
final name = 'liuwangshu'
//name = 'zhangwuji' ; / / complains
Copy the code
Const variables are compile-time constants. If const variables are at the class level, static const can be used.
const pi = 3.1415926;
const area = pi * 60 * 60;
Copy the code
Const is not only used to define constants. We can also use const to create values for constants.
var foo = const []; final bar = const []; const baz = [];// equivalent to 'const []'
Copy the code
6. Basic data types
Dart’s basic data types include Number, String, Boolean, List, Set, Map, Symbol, and Runes.
6.1 Number
There are two types of number:
- Int: Integer value not larger than 64 bits, depending on platform. On the Dart VM, the values can be -2^ 63 to 2^ 63-1, or -2^53 to 2^ 53-1 if compiled to JavaScript.
- Double: a 64-bit floating point number that complies with IEEE 754 standards.
6.2 the String
The Dart string is a sequence of utF-16 encoded characters. Strings can be created using either single or double quotation marks:
var s1 = 'Single quotes apply to string literals';
var s2 = "Double quotation marks also work.";
Copy the code
You can use expressions in strings: ${expression}. If the expression is an identifier, you can omit {}.
var s = 'Change the world';
assert('Zhang Wuji's $s'= ='The Great Shift of Zhang Wuji');
Copy the code
You can create a multi-line string object with three single quotes or three double quotes:
Var s1 = "first row second row"; Var s2 = """ first row second row """;Copy the code
6.3 Boolean
Dart is a strong bool check, and only true objects are considered true.
var name = 'Zhang Wuji';
if (name) {
print('Enlightened Lord');
}
Copy the code
The above code will not compile because name is a string, not a bool.
6.4 the List
Here is an example of a List:
var list = [1.2.3];
Copy the code
The index of the first element of List is 0, and the index of the last element is list.length-1.
var list = [1.2.3.4.5.6];
print(list.length);
print(list[list.length-1]);
Copy the code
6.5 the Set
A Set in Dart is an unordered Set.
var hero = ['Zhang Wuji'.'The wind is clear'.'Zhang SAN Feng'.'A lonely man seeking defeat'.'SAO feng'];
Copy the code
To create an empty set, precede {} with a type argument:
var heros= <String> {};
Copy the code
Add an entry to an existing set using the add() or addAll() methods:
var heros = <String>{};
heros.add(Stone Sky);
heros.addAll(hero);
Copy the code
6.6 the Map
A Map is a key-value pair object. The keys and values can be any type of object, each key is unique, and a value can occur more than once.
var player= {
// Keys Values
'20' : 'snow'.'3': Iverson.'40' : 'hill'.'8' : 'dull'.'55' : 'Mutombo'
};
Copy the code
The same function can be achieved using the Map constructor:
var player = new Map();
player['20'] = 'snow';
player['3'] = Iverson;
player['40'] = 'hill';
Copy the code
Function of 7.
Dart is a true object-oriented language, and functions belong to Function objects. This means that functions can be assigned to variables or treated as arguments to other functions.
void printName(String name) {
print('name is $name');
}
Copy the code
7.1 Optional Parameters
Optional parameters can be optional positional parameters or optional named parameters, but not both.
When calling a method with an optional named parameter, you can specify the parameter name in the form of paramName: value. In this way, you can learn the meaning of the parameter according to the paramName, which improves the readability of the code.
CoffeeFlavor (sugar:trueSugar:false);Copy the code
When defining functions, use {param1, param2… } to specify named parameters:
coffeeFlavor ({bool sugar , bool sugar}) {
}
Copy the code
Optional positional arguments Are made by placing function arguments in [] :
String go(String to, [String who]) {
var result = 'go to the $to';
if(who ! =null) {
result = '$result with $who';
}
return result;
}
Copy the code
7. 2 Default Parameter Values
You can use = to define default values for optional arguments, which must be compile-time constants. If no default value is provided, the default value is null.
String go(String to, [String who= 'liuwangshu']) {
var result = 'go to the $to';
if(who ! =null) {
result = '$result with $who';
}
return result;
}
String result= go ('beijing');
Copy the code
7.3 the main function
Every application needs a top-level main() function as an entry point to execute. The main() function returns void and takes an optional List
argument. The previous examples are verified by running the main function:
void main(a){
void printName(String name) {
print('name is $name');
}
printName('liuwangshu');
}
Copy the code
7.4 Anonymous Functions
Most functions have names, such as main() or printElement(). You can create anonymous methods without names in the format shown below.
([[Type] param1[, …]]) {
codeBlock;
};
Copy the code
The following code defines an anonymous function that takes I (which does not specify a type). Each element in the list is printed out by calling this function.
var list = ['Zhang Wuji'.'The wind is clear'.'Zhang SAN Feng'.'A lonely man seeking defeat'.'SAO feng'];
list.forEach((i) {
print(list.indexOf(i).toString() + ':' + i);
});
Copy the code
8. Flow control statements
Dart flow control statements are as follows:
- The if and the else
- The for loop
- While and do-while loops
- Break and continue
- The switch and the case
- assert
Most of these statements are similar to Java, with the focus on the for loop and switch statements.
8.1 a for loop
Standard for loops:
var message = new StringBuffer("Zhang Wuji");
for (var i = 0; i < 3; i++) {
message.write('! ');
}
Copy the code
Classes such as List and Set that implement the Iterable interface also support for-in traversal:
var hero = ['Zhang Wuji'.'The wind is clear'.'Zhang SAN Feng'.'A lonely man seeking defeat'.'SAO feng'];
for (var h in hero) {
print(h);
}
Copy the code
8.2 the switch and case
The Dart Switch statement compares integers, strings, or compile-time constants by using ==. The objects being compared must all be instances (not subclasses) of the same class, and this class is not allowed to overwrite ==. In addition, enumeration types are useful in Switch statements.
String today='Friday';
switch(today){
case 'Monday':
print('Monday');
break;
case 'Friday':
print('Friday');
break;
}
Copy the code
9. Catch exceptions
Catching an exception prevents the exception from being passed on.
try {
/ /...
} on OutOfLlamasException {
/ /...
} on Exception catch (e) {
print('Unknown exception: $e');
} catch (e) {
print('Something really unknown: $e');
}
Copy the code
Use either on or catch to declare a catch statement, or both. Where on specifies the exception type and catch catches the exception object. To ensure that some code executes with or without exceptions, you can use the finally statement.
try {
/ /...
} catch(e) {
print('Error: $e');
} finally {
/ /...
}
Copy the code
10. Add new functionality to the class
Dart is an object-oriented programming language that supports mixin-based inheritance mechanisms. Mixins can be understood as multiple inheritance, with one or more classes following the with keyword.
class Person{
run(){
print('run'); }}class Wushu{
use(){
print('Change the world'); }}class Zhangwuji extends Person with Wushu{
int age;
Zhangwuji(int age){
this.age=age; }}void main(a) {
var zhangwuji=new Zhangwuji(30);
zhangwuji.run();
zhangwuji.use();
}
Copy the code
Verified by the code above, the Zhangwuji class has the methods of the Person and Wushu classes.
11. Use of libraries
Use import to introduce a library, or Dart: Scheme for libraries built into the Dart language. For third-party libraries, you can use file system paths or package: scheme.
import 'dart:io';
import 'package:mylib/mylib.dart';
import 'package:utils/utils.dart';
Copy the code
Specify library prefixes If two imported libraries have conflicting names, you can use the library prefixes to distinguish them. For example, if library1 and library2 both have a class named Element, it could be used like this:
import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;
// ...
Element element1 = new Element(); // Use Element in lib1
lib2.Element element2 = new lib2.Element(); // Use Element in lib2
Copy the code
Importing a part of the library If you only use a part of the library, you can select the part to import. Show indicates that only the specified part is imported, and hide indicates that all but the specified part is imported.
// Import only foo
import 'package:lib1/lib1.dart' show foo;
// Import all parts except foo
import 'package:lib2/lib2.dart' hide foo;
Copy the code
Lazy-loaded libraries Lazy-loaded libraries mean that an application can reload libraries as needed. There are several scenarios in which lazy-loaded libraries are used:
- Reduce the initial startup time of the APP.
- Perform A/B testing, such as trying different implementations of various algorithms.
- Load little-used functionality.
To lazily load a library, import it using eferred AS:
import 'package:deferred/hello.dart' deferred as hello;
Copy the code
When needed, call the loadLibrary() function to load the library:
greet() async {
await hello.loadLibrary();
hello.printGreeting();
}
Copy the code
12. Asynchronous support
The Dart library contains many functions that return Future or Stream objects. These functions are asynchronous in that they return after a basic operation without waiting for the operation to complete, such as reading a file and returning after opening the file. Although it looks a bit like synchronous code, async and await code is truly asynchronous.
await readFile(a)
Copy the code
To use await, the method must have the async keyword:
FileOperate() async {
var file= await readFile(a)
// Other processing
}
Copy the code
13. Make classes callable
If a class in Dart implements a call() function, that class can be called as a method.
class JointFunction {
call(String a, String b, String c, String d) => '$a $b $c $d';
}
main() {
var jf = new JointFunction();
var out = jf("Put"."Hand"."To go"."To do");/ / 1
print('$out');
}
Copy the code
In the following example, the JointFunction class defines a call() function that takes three strings and concatenates them. This will call the JointFunction class in comment 1.
14. Create an instance
Dart Dart Dart Dart Dart Dart Dart Dart Dart Dart Dart Dart Dart Dart Dart Dart Dart
Element element = Element();
Copy the code
For Android development, the use of new may be more accustomed to a little more readable, not new appears more concise, as for the use of new depends on the requirements of the team and personal habits, there is no absolute good or bad.
A quick start with the Hello World Flutter Foundation and the Hello World Flutter Foundation Fundamental of Flutter (5) MaterialApp, Scaffold and AppBar of Material components Description the BottomNavigationBar, TabBar, Drawer foundation of the Flutter component (7) listed view, GridView, PageView Flutter Basics (8) Quick Start on Flutter Basics: Web request (Dio) and JSON data parsing Flutter foundation (12) Routing (page hopping) and data transfer Flutter foundation (13) Flutter and Android’s mutual communication
conclusion
There are many knowledge points about Dart, and only some of them are introduced here. If you want to know more about Dart, you can check the official documents. You can learn about Dart while writing about Flutter, rather than just focusing on the details of Dart.
Share big front-end, Android, Java and other technologies to help 50,000 programmers grow and advance.