Dart language foundation for Flutter development

Dart Language Basics –

The main() function, whether in Dart or Flutter , must need a top-level main() function, which is the entry function of the entire application, the return value of the main() function is void, and an optional parameter, the parameter type is List.

main() {

}
  • 1
  • 2
  • 3

1 Basic data types

1.2 Dart has the following built-in data types

In Dart, it is strongly typed, and there is also a mechanism for automatically inferring types.

typeillustrate
NumberCan be understood as a numeric data type
Stringstring
Booleanboolean type
Listarray
Mapkey-value data type
1.3 Number

Including two types, int integer, double floating point

1.4 Boolean

The value is only true false

1.5 List is similar to arrays and collections in java
var list = [ 1 , 2 , 4 , 5 ] ;
  • 1
1.6 Map is similar to hashmap in java
1.7 Strings
// 1. Dart can use single or double quotes to create strings 
var s1 =  "hello" ; 
var s2 =  'world' ;

// 2. Similar to Python, Dart can use triple quotes to create strings containing multiple lines. Here, three double quotes are used. Of course, three single quotes can also be used. 
var multiLine1 =  "" "Multi-line string content
Multi-line string content
Multi-line string content
Multi-line string content
""";

var multiLine2 =  '' ' You can also use three single quotes to create a
Contains multiple lines of string content
'' ' ;

// 3. Similar to Python, you can also add `r` in front of the string literal value to create the original string, then the special characters in the string can be escaped without escaping 
var path = r 'D:\workspace\code' ;

// 4. Dart supports using "+" operator to concatenate strings 
var greet =  "hello"  +  " world" ;

// 5. Dart provides the interpolation expression "${}", which can also be used to concatenate strings 
var name =  "Wang Wu" ; 
var aStr =  "hello,${name}" ; 
print ( aStr ) ;     // hello, Wang Wu

// When only the variable value is taken, the curly braces can be omitted 
var aStr2 =  "hello,$name" ;  // hello,Wang Wu

// When concatenating an expression, the curly braces cannot be omitted 
var str1 =  "link" ; 
var str2 =  "click ${str1.toUpperCase()}" ; 
print ( str2 ) ;    // click LINK

// 6. Unlike Java, Dart uses "==" to compare the contents of strings 
print ( "hello"  ==  "world" ) ; 
-- -- -- -- -- -- -- -- -- -- -
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
1.4 map is an associative array, equivalent to HashMap in Java
// 1. Create Map by literal 
var gifts =  { 
  'first'  :  'partridge' , 
  'second' :  'turtledoves' , 
  'fifth'  :  'golden rings' 
} ;

// 2. Use the constructor of the Map class to create an object 
var pic =  new  Map ( ) ; 
// Add key-value pairs to the Map 
pic [ 'first' ]  =  'partridge' ; 
pic [ 'second' ]  =  'turtledoves' ; 
pic [ 'fifth' ]  =  'golden rings' ;

// 3. Get the length of the Map 
print ( pic . length ) ;

// 4. Find Map 
pirnt ( pic [ "first" ] ) ; 
print ( pic [ "four" ] ) ;     // return null if key does not exist

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
2 Declaration of basic variables

There are two ways to define variables in Dart. One is the way commonly used in statically typed languages, which explicitly specifies the variable type, and the other is the common way in dynamic languages, which is automatically inferred by vm without specifying the type.

// 1. Define the variable by explicitly specifying the type 
String name =  "Zhang San" ; 
num age =  18 ;

// 2. Use the keyword var, do not specify the type 
var address =  "Shennan Avenue" ; 
var id =  100 ;

/* Use var to define variables, even if the type is not explicitly specified, the type is fixed once assigned
 * Therefore variables defined with var cannot change the data type
 */ 
var number =  19 ; 
// The following code is wrong and cannot be run, the number variable has been determined to be of type int 
number =  "2019" ;


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

If you want to dynamically change the data type of a variable, you should use dynamic or Object to define the variable.
dynamic means any, it is different from var, var will automatically infer the type to come up with a certain type, and dynamic can represent any, as opposed to any in Typescript.

// dynamic declaration variable 
// initialized here is a 
dynamic of type sting var1 =  "hello" ; 
// changed to type int again here 
var1 =  19 ; 
print ( var1 ) ;     // 19

// Object declares variable 
Object var2 =  20 ; 
var2 =  "Alice" ; 
print ( var2 ) ;     // Alice

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

There are also two ways to define constants in Dart. One uses the final keyword, which is the same as the usage in Java. A final variable can only be assigned once; the other is the Dart method, which is defined using the const keyword.

// 1. Use the final keyword to define the constant 
final height =  10 ;

// 2. Use the const keyword to define constants 
const pi =  3.14 ; 
//It should be noted that the constants defined by final are run-time constants, while the const constants are compile-time constants, that is to say, when the final constant is defined, its value can be A variable, and a constant defined by const, its value must be a literal constant value.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
3 Function usage in Dart

From the developers of java or oc, when a function is declared with a return value, it must have return. We can understand it as a very rigorous programming language, but in Dart language, we can understand it as a non-rigorous programming function

// declare the return value
int add(int a, int b) {
  return a + b;
}
// do not declare return value
add2(int a, int b) {
  return a + b;
}

// => is shorthand for return statement
add3(a, b) => a + b;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

It can be called directly when used in the main function var add2 = add(1, 2);

3.1 Named parameters

As the name implies, a name is given to the parameter as follows


// a parameter
test({String name}){
  print("hello, my name is $name and age is 0");
}
// multiple parameters
test({String name,int age}){
  print("hello, my name is $name and age is $age");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

The difference from the general function declaration is that there is an extra {}} at the declared parameter type
and add4(name: "zhansan", age: 3) when calling;
that is, the parameter must be added before the input parameter value. corresponding name

// default values ​​for named parameters
// cannot be written as: int add({a: int, b: int = 3})
int add({int a, int b = 3}) {
  return a + b;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
3.2 Positional parameters

The parameter enclosed in square brackets [] is the positional parameter of the function, which means that the parameter can be passed or not, and the positional parameter can only be placed at the end of the parameter list of the function.

// There can be multiple positional parameters, such as [String a, int b]
test(String name, int age, [String hobby]) {
  StringBuffer sb = new StringBuffer();
  sb.write("hello, this is $name and I am $age years old");
  if (hobby != null) {
    sb.write(", my hobby is $hobby");
  }
  print(sb.toString());
}


// default values ​​for named parameters
// cannot be written as: int add({a: int, b: int = 3})
int add({int a, int b = 3}) {
  return a + b;
}

// default values ​​for positional parameters
int sum(int a, int b, [int c = 3]) {
  return a + b + c;
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
3.3 Functions as parameters
main() {
  // An anonymous function is passed in here
  test((param) {
    // print hello
    print(param);
  });
}


test(Function callback) {
  callback("hello");
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
4 Operators
+ , - , * , / , % are the same as Java language
  • 1

There is another integer division operator ~/ in Dart. The difference from the ordinary division sign is that the result of the division is rounded and returned.

typeillustrate
asfor type conversion
isReturns True if the object is of the specified type
is!Returns True if the object is not of the specified type

obj is T is true when obj implements T's interface. Similar to instanceof in Java.
Dart uses the as operator to convert an object to a specific type. If it cannot be converted, an exception will be thrown, so it is best to use the is operator to detect before conversion.

// Convert p to Person type and then operate 
( p as Person ) . name =  'Bruce' ;
  • 1
  • 2
5 Control Flow

if / else switch for /while try / catch statement is similar to Java, try / catch statement may be slightly different

// if else statement
  int score = 80;
  if (score < 60) {
    print("so bad!");
  } else if (score >= 60 && score < 80) {
    print("just so so!");
  } else if (score >= 80) {
    print("good job!");
  }

  // switch statement
  String a = "hello";
  // The data type in the case statement must be the same as the type in the switch
  switch (a) {
    case "hello":
      print("haha");
      break;
    case "world":
      print("heihei");
      break;
    default:
      print("WTF");
  }

  // for statement
  List<String> list = ["a", "b", "c"];
  for (int i = 0; i < list.length; i++) {
    print(list[i]);
  }
  for (var i in list) {
    print(i);
  }
  // Arrow function arguments here must be enclosed in parentheses
  list.forEach((item) => print(item));

  // while statement
  int start = 1;
  int sum = 0;
  while (start <= 100) {
    sum += start;
    start++;
  }
  print(sum);

  // try catch statement
  try {
    print(1 ~/ 0);
  } catch (e) {
    // IntegerDivisionByZeroException
    print(e);
  }
  try {
    1 ~/ 0;
  } on IntegerDivisionByZeroException { // Catch an exception of the specified type
    print("error"); // print out error
  } finally {
    print("over"); // print out over
  }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
6 Classes in dart
6.1 Class Definition and Constructor

Classes in Dart have no access control, so you don't need to decorate member variables or member functions with private, protected, public, etc. A simple class

class Person {
  String name;
  int age;
  String gender;
  //Construct without parameters
  Person();
  //Construction method
  Person(this.name, this.age, this.gender);
  // named construct
  Person.builder(){};
  // member method
  test() {
    print("hello, this is $name, I am $age years old, I am a $gender");
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

The three parameters passed in by the constructor here are this.xxx , and there is no method body wrapped in curly brackets {}.
This syntax is Dart's unique and concise way of declaring constructors, which is equivalent to the following code:

Person(String name, int age, String gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Test in main() function

// can be assigned directly in the construction
var p = new Person("zhangsan", 20, "male");
// hello, this is zhangsan, I am 20 years old, I am a male
p.test();

//You can also call update assignment separately
p.age = 22;
p.gender = "female";
p.test();
 // hello, this is zhangsan, I am 22 years old, I am a female

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
6.2 Use the extends keyword to do class inheritance in Dart
6.3 Abstract classes and abstract methods

Use abstract to decorate a class, then this class is an abstract class. An abstract class can have abstract methods and non-abstract methods. An abstract method has no method body and needs to be implemented by subclasses.

abstract class Person {
  // Abstract method, no method body, need subclass to implement
  void doSomething();
  // normal method
  void greet() {
    print("hello world!");
  }
}

class TestPerson extends Person {
  // Implements the abstract method of the parent class
  void doSomething() {
    print("I'm doing something...");
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
7 Dart Libraries

Dart currently has many libraries available to developers. Many functions do not need to be implemented by developers themselves. They only need to import the corresponding package. Use the import statement to import a package or import a specific class.

//Basic import method
import 'package:lib1/lib1.dart';
//You can use the as keyword to set a prefix, or alias, for an imported package
import 'package:lib2/lib2.dart' as lib2;
// only import foo
import 'package:lib1/lib1.dart' show foo;
// import everything except foo
import 'package:lib2/lib2.dart' hide foo;
//Use deferred as when importing a package to make the package lazily loaded. Lazy-loaded packages will only be loaded when the package is used, not at the beginning
import 'package:greetings/hello.dart' deferred as hello;



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
8 Dart Asynchronous

Dart provides asynchronous operations such as async await in ES7, which are often encountered in Flutter development, such as network or other IO operations, file selection, etc., which require asynchronous knowledge.
Async and await often appear in pairs. If there is a time-consuming operation in a method, you need to set the method to async, and add the await keyword to the time-consuming operation. If the method has a return value, you Need to stuff the return value into the Future and return

Future checkVersion() async {
  var version = await lookUpVersion();
  // Do something with version
}

  • 1
  • 2
  • 3
  • 4
  • 5

Simulate a network request

Future<String> getNetData() async{
  http.Response res = await http.get("http://www.baidu.com");
  return res.body;
}

  • 1
  • 2
  • 3
  • 4
  • 5

Tags: Dart language foundation for Flutter development

A full set of tutorials for Flutter project development flutter dart language

Related: Dart language foundation for Flutter development