1. An overview of the

Dart is the official application development language for Fuchsia, Google’s next-generation operating system, but the development language for Flutter, the cross-platform App framework. It is an object-oriented language that uses C-style syntax and combines features of Javascript, Python, Java, and other languages.

If you are familiar with these languages, you can get started quickly.

2. If you know, you will

2.1. Statement terminator

Dart, like C, starts all statements with; The end.

2.2. The annotation

Same as Javascript, single-line // and multi-line /* */.

If you want to support document generation tools, use // for single-line comments and /** */ for multi-line comments, for example:

/// This is a documentation comment

/** This , too, isa
  documentation comment.
*/
Copy the code

2.3. Variable declarations and types

Dart is a strongly typed language, meaning that all variables are typed.

As with C, you can specify type

variable when declaring variables; , such as:

int a = 3;
Copy the code

You can also use var a = 3 just like in Javascript; In this case, Dart deduces the type of the variable from the rvalue of the assignment statement. In this case, it deduces that variable A is int. The variable is then typed and cannot be assigned to any other type. For example, in this example, assigning a String Value to a will fail: a = “String Value”; .

If a variable is declared as dynamic, it can be assigned to a value of one type at any time. For example:

dynamic x = 42;
x = "Hello World";
Copy the code

Like Java, everything in Dart is an Object that ultimately inherits from the Object class, so declaring variables of type Object is similar to declaring variables of type Dynamic. You can assign values of any type, such as:

Object x = 42;
x = "Hello World";
Copy the code

The dynamic type tells Dart not to check the type of a variable. That is, type detection is turned off, so a reference to a method that does not exist on a Dynamic variable will pass the compilation, but will fail at runtime. A reference to a method that does not exist on the Object class will fail the compilation.

2.4. Constants and final values

Like Java, constant values are decorated with const. Constant values are determined at compile time and cannot be modified, as in:

const x = "Hello";
const String y = "world";
Copy the code

Final variables can be assigned at run time, but only once. For example, if you want to determine the startup time of the program, you can declare it as a final variable, for example:

final x = DateTime.now();
Copy the code

Const modifies not only variables but also values, as in:

List lst = const [1.2.3];
lst[0] = 999; // compile error
Copy the code

Type 2.5.

It’s basically like starting with lower case, int, double, num, bool, where num is the parent of int, double. Other types start with a capital case, such as String, List, Map.

2.5.1. Digital type

Like C, int, double, num all support +, -, *, /, %. The only special numeric operator is ~/, which returns the integer part of the division result. It works like Python’s // operator, as in:

int x = 3;
double y = 2.0;
x = x ~/ y;
print(x); / / 1
Copy the code

Dart x = x + y can be abbreviated as x += y, as in C. This abbreviation also applies to the -, *, /, % and ~/ operators. For example, x = x ~/ y can be written as x ~/= y.

C also has similar v++, ++v, v–, –v and other postfix operators and tervariate conditional expressions such as: x = a? B: c.

Dart also supports a unique binary conditional expression, such as x = a?? b; , indicates that x is assigned to a if a has a value (that is, it is not null and the default value is null if the declared variable is not initialized), otherwise it is assigned to B.

2.5.2. String type String

As in Javascript, strings can be quoted either as single ‘XXX’ or as double ‘XXX’. If a string contains a variable reference of the form ${val}, the resulting string will be automatically replaced with the value of the variable. This is a convenient feature, such as:

String name = "Haiiiiiyun";
String greeting = "Hello ${name}"; // Hello Haiiiiiyun
String greeting = "Hello $name"; // You can also omit {} and use $var
Copy the code

Strings and numbers can be converted to and from each other, for example:

int i = 42;
double d = 4.2;
String si = i.toString(); 42 "/ /"
String sd = d.toString(); / / "4.2";

int i2 = int.parse(si); / / 42
double d2 = double.parse(sd); / / 4.2
Copy the code

2.5.3. Boolean bool

There are only two values: true and false. Note that the value of a judgment expression cannot be converted to bool stealthily in conditions such as if while.

if (1) { // 
    print("true");
}
Copy the code

Does not compile because 1 cannot be converted to bool true.

2.5.4. Enumerated Enum

Type C. Enum Defines the enumeration type, for example, enum Week{Mon, Tue, Wed, Thu, Fri, Sat, Sun}. .

Each value has an index value, for example, week.mon. index is 0, week.tue. index is 1, and so on. Enumerated values apply to switch statements.

2.5.5. The List

A List is like an array in Javascript. It is ordered, so there is an indexOf method.

List lst = ['a'.'b'.'c'];
lst.add('d'); // ['a', 'b', 'c', 'd']
lst.removeLast(); // ['a', 'b', 'c']
print(lst.indexOf('a')); / / 0
Copy the code

A Set, like a Python Set, is an unordered array, and its elements are not duplicated:

Set chars = Set(a); chars.addAll(["a"."b"."c" ]);
chars.add("a"); // still ["a", "b", "c"]
chars.remove("b"); // ["a", "c"]
chars.contains("a")); // true
chars.containsAll([ "a"."b" ])); // false
Copy the code

2.5.6. The Map

Similar to dict in Javascript, the operations are:

Map<String.String> countries = Map(a); countries['India'] = "Asia";
countries["Germany"] = "Asia"; // wrong
countries["France"] = "Europe";
countries["Brazil"] = "South America";

if (countries.containsKey("Germany")) {
    countries["Germany"] = "Europe"; // update
    print(countries); // {India: Asia, Germany: Europe, France: Europe, Brazil: South America}
}

countries.remove("Germany");
print(countries); // {India: Asia, France: Europe, Brazil: South America}
Copy the code

2.6. Type testing and conversion

Is keyword for type testing, as keyword for type conversion, such as

// Pig is a subclass of Animal

if(animal is Pig) {
    (animal as Pig).oink(); / / sound
}
Copy the code

2.7. Process control

If and else are exactly the same as in C. Conditional expressions can also be used | |, && and! Make combinations.

Switch is the same as in C.

2.8. Cycle

The while and do while loops are exactly the same as in C. The continue and break statements are also used.

2.8.1 for loop

The first for loop form and type C, as in:

for (var i=0; i<10; i++){
    print(i);
}
Copy the code

The second for-in form applies to iterables such as List, Iterator, and so on:

List lst = ['a'.'b'.'c'];
for (var char in lst) {
    print(char);
}
Copy the code

2.9 Exception Handling

Exception handling is similar to Java. The base classes are Error and Exception. To catch certain types of exceptions, use on

catch(e). If you don’t care what type of Exception you catch, use catch(e). Code in the finally section executes last, whether or not an exception is caught, as in:

try {
    somethingThatMightThrowAnException();
} on FormatException catch (fe) {
    print(fe);
} on Exception catch (e) {
    Print("Some other Exception: " + e);
} catch (u) {
    print("Unknown exception");
} finally {
    print("All done!");
}
Copy the code

3. Functions and objects

All variables in Dart are objects, so functions are objects of type Function.

Function definitions are similar to those in C, such as:

int add(int a, int b)
{
    return a + b;
}

Copy the code

That is, when defining a function, you specify the return value type of the function and the type of its parameters. If no return value type is specified, the default is void.

Like C, the main(List

args) function is the entry function to the program.

3.1 Naming function parameters

In a normal function call, the parameter values are determined by their positions, as in the preceding function call:

int x = add(1.2); / / 3
Copy the code

Named function arguments are specified in {}, such as:

int add2(int init, {int a, int b}){
    return init + a + b;
}

print(add2(1, b:2, a:1)); / / 4
Copy the code

The named parameter value is specified in the form x:y when called, and the parameter position is independent of the position at definition, but must be after the normal position function value.

3.2. Parameter Default values

You can specify default values for named parameters, such as:

int add3({int init=0.int a, int b}){
    return init+a+b;
}

print(add3(a:1, b:2)); / / 3
print(add3(init:10, a:1, b:2)); / / 13
Copy the code

3.3. Optional Parameters

Place the argument in [] to specify that it is an optional argument and can be called without providing a parameter value, for example:

String add4(int a, int b, [String c]){
    return "$c: ${a+b}";
}

main(){
    print(add(1.2));
    print(add2(1, a:1,b:2));
    print(add3(a:1, b:2));
    print(add3(init:10, a:1, b:2));

    print(add4(1.2)); // null: 3
    print(add4(1.2."Sum")); // Sum: 3
}
Copy the code

3.4. Anonymous functions

Similar to anonymous functions in Javascript and Java, the created anonymous Function can be assigned to a variable of Function, which is then called just like a normal Function, for example:

Function add5 = (int a, int b) {
    return a+b;
};

print(add5(1.2)); / / 3
Copy the code

If the function body, as in this example, is just a return statement, it can be abbreviated as fat arrow (similar to Python lambda functions) :

Function add6 = (int a, int b) => a+b;
print(add6(1.2)); / / 3
Copy the code

3.5. Higher-order functions

Functions are objects that can be passed as function parameter values. A function that accepts the value of the function as an argument is a higher-order function.

Such as:

Function add6 = (int a, int b) => a+b;

int operator(Function op_fun, int a, int b)
{
    return op_fun(a, b);
}

print(operator(add6, 1.2)); / / 3
Copy the code

The operator function here is a higher-order function.

3.6. The Closure Closure

A closure is a special function, also called a closure function. When a closure function is defined, the value of the variable in its parent scope is fixed by the closure function, so that when the closure function is called, the value of the variable at the time of definition is also used.

This is especially true when defining closure functions inside functions (functions can be defined inside function bodies), as in:


Function adder(int step)
{
    return (a) => a + step;
}

var adder1 = adder(1);
print(adder1(1)); / / 2

var adder10 = adder(10);
print(adder10(1)); / / 11
Copy the code

The closure function adder1 fixes the step value to 1 as defined, while adder10 fixes the step value to 10.

4. Classes and object-oriented

Like Java, classes are defined with class definitions, such as:

class Animal {
    int numLegs = 0;
    int numEyes = 0;

    Animal(int numLegs, int numEyes){
        this.numLegs = numLegs;
        this.numEyes = numEyes;
    }

    void eat() {
        print("Animals eat everything depending on what type it is."); }}var a1 = new Animal(4.2);
var a2 = Animal(4.2); // The new keyword can be omitted
Copy the code

Class instances are also created using new ClassName(arG), where the new keyword can be omitted, so that creating class instances and calling functions are formally the same.

4.1 Attributes and methods

Where numLegs and numEyes are attributes, you can directly access the value of the attribute in the instance, for example:

var a1 = new Animal(4.2);
a1.numLegs = 2;
print(a1.numLegs); / / 2
Copy the code

Where eat() is a method that can be called on a class instance in the same way as a function call.

When accessing properties and methods, an exception is thrown if the object is empty, similar to Typescript, Dart? The. Operator is used to access object properties, but does not access them if the object is null, thus avoiding throwing an exception:

var a1 = Animal(4.2);
a1 = null;
print(a1? .numLegs);// No exception will be thrown.
Copy the code

Static properties and methods are modified with static. These are class-level properties and methods that can be accessed directly on the class:

class Circle {
    static const pi = 3.14;
    static void drawCicle() {
        / /...}}print(Circle.pi); / / 3.14
Circle.drawCicle();
Copy the code

4.2. Construction method

A constructor can have parameters. For example, the constructor in this example only sets the value of each property of the class. A constructor like this can be abbreviated as:

class Animal {
    int numLegs;
    int numEyes;

    Animal(int this.numLegs, int this.numEyes);

    void eat() {
        print("Animals eat everything depending on what type it is."); }}Copy the code

Multiple constructors can be defined, either with the same method name as the class

or as

. Is a prefix, for example:

class Animal {
    int numLegs = 0;
    int numEyes = 0;

    Animal(int this.numLegs, int this.numEyes); // constructor

    Animal.namedConstructor(int this.numLegs, int this.numEyes) { // Another constructor
    }

    void eat() {
        print("Animals eat everything depending on what type it is."); }}Copy the code

4.2.1. Default constructor

Similar to C++, if no constructor is declared, the compiler automatically generates a default constructor with no arguments, which also calls the parent class’s no-argument constructor.

4.2.2. Constructors cannot be inherited

A subclass cannot inherit the constructor of its parent class. The constructor of a subclass calls the constructor of its parent class through super and, like in C++, places the parent call in an initializer, as in:

class Cat extends Animal {
    Cat(): super(4.2) {}}Copy the code

The code in the initialization list is executed first.

4.2.3. Redirect constructor

A constructor calls only another constructor through an initializer list, without a method body, as in:

class Animal {
    int numLegs = 0;
    int numEyes = 0;

    Animal(int this.numLegs, int this.numEyes); // constructor

    Animal.cat(): this(4.2); // Redirect the constructor

    void eat() {
        print("Animals eat everything depending on what type it is."); }}Copy the code

4.2.4. Getter and setter

import 'dart:math';

class Square {
    double width;

    
    Square(this.width);

    double get area => width * width;

    set area(inArea) => width = sqrt(inArea);
}

var s = Square(5);
print(s.area); / / 25.0

s.area = 16;
print(s.width); / / 4.0
Copy the code

Use the get keyword to set the getter and the set keyword to set the setter.

4.3. A subclass

As with Java, the syntax for generating subclasses is Class SubClass extends SuperClass {}. Dart does not support multiple inheritance and extends only from a parent class.

4.4. An abstract class

Like Java, abstract classes are decorated with abstract. Abstract classes can declare only methods or have a default implementation:

abstract class Shape {
    double area(); // Only declarations

    void draw(){ // There is a default implementation body
        print("draw here"); }}Copy the code

Abstract classes cannot be instantiated.

4.4. The interface interface

Dart does not distinguish between classes and interfaces. Common classes and abstract classes are both interfaces. Classes cannot be multiinherited, but they can implement multiple interfaces, which are separated by the implements keyword.

abstract class Shape {
    double area(); // Only declarations

    void draw(){ // There is a default implementation body
        print("draw here"); }}class Circle implements Shape {

    @override
    double area(){
    }

    @override
    void draw(){ // There is a default implementation body
        print("draw here"); }}Copy the code

If you implement an interface with implements, you must implement (override) all methods and properties in the interface, regardless of whether there is a default implementation in the interface.

4.6. A mixin

Mixins are a way to reuse code.

Dart does not distinguish classes from mixins; both generic and abstract classes are mixins. A class cannot inherit multiple mixins, but it can introduce multiple mixins, separated by, using the with keyword, as in:

class Shape {
    double area() {
    }

    void draw(){
        print("draw here"); }}class Circle with Shape {}var c = Circle();
c.draw();
Copy the code

Unlike interfaces, subclasses need not implement the methods already implemented in mixins.

4.7. Special methods

4.7.1 the call ()

If the call method is implemented in a class, the class instance can be called like a function, when the call(…) in the instance is actually executed. Methods, such as:

class CallableClassWithoutArgument {
    String output = "Callable class";

    void call() {
        print(output); }}class CallableClassWithArgument {
    call(String name) => print("$name");
}

var withoutArgument = CallableClassWithoutArgument();
withoutArgument(); // Callable class

var withArgument = CallableClassWithArgument();
print(withArgument("John Smith")); // John Smith
Copy the code

4.7.2 Operator overloading methods

Dart class can override the following operators: <, >, < =, > =, ~ /, /, +, -, *, %, ^, |, &, < <, > >, [], [] =, ~, = =.

Overloaded methods are methods that implement operator and operation symbol names in a class, such as:

class MyNumber {
    num val;
    num operator + (num n) => val * n;
    MyNumber(this.val);
}

MyNumber mn = MyNumber(5);
print(mn+2); / / 10
Copy the code

Here, the + function is reloaded as the multiplication function.

5. Package

Each DART file is a package.

Import other packages as ‘URL’ where the URL is schema:path and the schema values are:

  • dart: Dart built-in packages, such asimport 'dart:math'
  • package: third-party package, such asimport 'package:flutter/material.dart'
  • No Schame section: indicates that only relevant packages in the current project are imported, such asimport 'NotesModel.dart'

Dart “show NotesModel, NotesModel; . Dart “show NotesModel, NotesModel; dart” show NotesModel; .

If the attribute names in the package conflict, you can rename the imported package using the as keyword, for example, import ‘dart:math’ as math; .

resources

  • Flutter website
  • Flutter Community Chinese resources