Dart (1)


Foreword 1: I will update some columns of flutter text tutorials in succession in the next period

Update progress:At least two articles per week;

Update location:The first time is in the official account, and the second day is updated in nuggets and places of thought.

More communication:You can add my wechat 372623326 and follow my micro blog: Code why

I hope you canHelp forward, click to seeGive me more creative power.

Foreword 2: in a few years, you will find that the loss of choosing the wrong company and industry is far greater than choosing the wrong language.

And the computer industry, only one programming language is obviously unrealistic, receiving a new language, not as difficult as you think!

1、 Dart introduction and installation

1.1. Know dart

It is a fact that Google has chosen dart for flutter. No matter how much you want to develop flutter in a language you are familiar with, such as JavaScript, Java, swift, C + +, etc., it is not allowed at least at present.

In explaining dart, I’ll assume that you already haveCertain programming language foundation, such as JavaScript, Java, python, C + +, etc.

In fact, if you’re dealing with programming languagesEnough confidenceDART’s learning process can even be ignored directly:

  • Because after you’ve learned n programming languages, you’ll find outThe difference is not big
  • Nothing but that.Grammatical differences+Some languages have certain characteristics, but some languages do not have certain characteristics;
  • When I first came into contact with flutter, I didn’t specifically look at DART’s grammar, but I went back to understand some grammar when I was not very proficient;

So, if you know enough about programming language, you can skip our next dart study:

  • I will not list all the features one by one, I will pick out the more important language features to explain specifically;
  • Some features may be explained separately when some knowledge of flutter is explained later;

Now, let’s start with dart!

1.2. Install dart

Why do I need to install dart?

In fact, dart is built-in when installing the flutter SDK. We can write and run dart directly using flutter.

However, if you want to learn dart alone and run your own dart code, you’d better install a dart SDK.

Download dart SDK

To the official dart, download the corresponding dart according to different operating systems

  • Official website: https://dart.dev/get-dart

No matter what operating system it is, there are two ways to install it:Installation by toolsandDownload SDK directly and configure environment variables

1. Installation by tools

  • Windows can use chocolate
  • Mac OS can use homebrew
  • The website of the official website for specific installation and operation has a detailed explanation

2. Download SDK directly and configure environment variables

  • Download address: https://dart.dev/tools/sdk/ar
  • I used this installation.
  • After downloading, you can configure the environment variables according to the path.

1.3. Vscode configuration

In learning dart, I usedVSCodeAs editor

  • On the one hand, it’s very convenient to write code, and I also like the interface style
  • On the other hand, I can quickly see the effect of my code writing on the terminal

To write dart with vscode, you need to install the dart plug-in: I currently have four plug-ins for this vscode

  • Dart and flutter plug-ins are for flutter development
  • Atom one dark theme is one of my favorite themes
  • Code runner can click the button in the upper right corner to let me run the code quickly

Dart (1)

2、 Hello dart

2.1. Hello World

Next, you can get to the point. Learn programming languages, starting with the ancestral Hello world.

Create a new one in vscodehelloWorld.dartFile, add the following:

main(List<String> args) {
  print('Hello World');

Then execute at the terminaldart helloWorld.dart, you can seeHello WorldThe result.

After the execution, how much information can you get from the programming language you learned before?

2.2. Analysis of procedures

Next, it is my own summary:

  • 1、 The entry of dart language is also a main function, which must be displayed for definition;
  • 2、 DART’s entry functionmainThere is no return value;
  • 3、 Pass tomainThe command-line parameters of are passed through theList<String>Done.

    • It can be understood from the face valueListIs the collection type in dart.
    • Each of themStringAll means pass tomainA parameter of;
  • 4、 When defining a string, you can use single or double quotation marks;
  • 5、 Each line of statements must end with a semicolon. Many languages do not need a semicolon, such as swift and JavaScript;

3、 Defining variables

3.1. Explicit

The format of variable declaration is as follows:

Variable type variable name = assignment;

Example code:

String name = 'coderwhy';
int age = 18;
double height = 1.88;
Print ('${name}, ${age}, ${height}'); // the splicing method will be explained later

Note: the defined variable can modify the value, but cannot assign other types

String content = 'Hello Dart';
Content ='Hello world '; // correct
Content = 111; // wrong, assign an int value to a string variable

3.2. Type inference

The type deducts and declares variables in the following format:

Var / dynamic / const / final variable name = assignment;

3.3.1. Use of VaR

Examples of using VAR:

  • RuntimeType is used to get the current type of the variable
var name = 'coderwhy';
name = 'kobe';
print(name.runtimeType); // String

Wrong use of VaR:

var age = 18;
Age = 'why'; // string cannot be assigned to an int type

3.3.2. Use of dynamic

If you do want to do so, you can use dynamic to declare variables:

  • But in development, dynamic is usually not used, because variables of type can bring potential danger
dynamic name = 'coderwhy';
print(name.runtimeType); // String
name = 18;
print(name.runtimeType); // int

3.3.3. Use of final & const

Both final and const are used to define constants, that is, after the definition, the values cannot be modified

final name = 'coderwhy';
Name ='kobe '; // wrong way

const age = 18;
Age = 20; // wrong way

What’s the difference between final and const?

  • When const assigns a value, the content of the value must be determined during compilation
  • When final is assigned, it can be acquired dynamically, such as assigning a function
String getName() {
  return 'coderwhy';

main(List<String> args) {
  Const name = getname(); // wrong way, because you need to execute the function to get the value
  Final name = getname(); // correct way

Small cases of final and const:

  • First, const cannot be assigned to datetime. Now()
  • Second, once final is assigned, it will have a certain result and will not be assigned again
//Const time = datetime. Now(); // wrong assignment method
final time = DateTime.now();
print(time); // 2019-04-05 09:02:54.052626

sleep(Duration(seconds: 2));
print(time); // 2019-04-05 09:02:54.052626

Const is placed on the right side of the assignment statement to share objects and improve performance

  • I’ll talk about this concept again later when I talk about constant constructors of classes
class Person {
  const Person();

main(List<String> args) {
  final a = const Person();
  final b = const Person();
  print(identical(a, b)); // true

  final m = Person();
  final n = Person();
  print(identical(m, n)); // false

4、 Data type

4.1. Number type

For numerical value, we don’t care about whether it has symbols, and the width and precision of data. Just remember to use integersintFor floating-point numbersdoubleAll right.

But, to be clear, it’s dartintanddoubleThe representable range is not fixed, it depends on the platform on which dart is running.

//1. Integer type int
int age = 18;
int hexAge = 0x12;

//2. Floating point type double
double height = 1.88;

Conversion between string and number:

//String and number conversion
//1. String to number
var one = int.parse('111');
var two = double.parse('12.22');
print('${one} ${one.runtimeType}'); // 111 int
print('${two} ${two.runtimeType}'); // 12.22 double

//2. Number to string
var num1 = 123;
var num2 = 123.456;
var num1Str = num1.toString();
var num2Str = num2.toString();
Var num2strd = num2.tostringasfixed (2); // keep two decimal places
print('${num1Str} ${num1Str.runtimeType}'); // 123 String
print('${num2Str} ${num2Str.runtimeType}'); // 123.456 String
print('${num2StrD} ${num2StrD.runtimeType}'); // 123.46 String

4.2. Boolean type

In the boolean type, dart provides a bool type with values of true and false

//Boolean type
var isFlag = true;
print('$isFlag ${isFlag.runtimeType}');

Note: in dart, you cannot judge whether it is true or not

DART’s type security means you can’t use code like if (non Boolean value) or assert (non Boolean value).

var message = 'Hello Dart';
  //Wrong writing
  if (message) {

4.3. String type

The dart string is a sequence of utf-16 encoding units. You can use single or double quotes to create a string:

//1. How to define strings
var s1 = 'Hello World';
var s2 = "Hello Dart";
var s3 = 'Hello\'Fullter';
var s4 = "Hello'Fullter";

You can use three single or double quotes to represent multiline strings:

//2. How to represent multiline strings
var message1 = '''
Ha ha ha
Hehe hehe '';

String concatenation with other variables or expressions: use ${expression}, if the expression is an identifier, {} can be omitted

//3. Splicing other variables
var name = 'coderwhy';
var age = 18;
var height = 1.88;
print('my name is ${name}, age is $age, height is $height');

4.4. Set type

4.4.1. Definition of set type

For collection types, dart has built-in three most commonly used types:List / Set / Map

Among them,ListIt can be defined as follows:

//List definition
//1. Use type derivation definition
var letters = ['a', 'b', 'c', 'd'];
print('$letters ${letters.runtimeType}');

//2. Clearly specify the type
List<int> numbers = [1, 2, 3, 4];
print('$numbers ${numbers.runtimeType}');

Among them,setIt can be defined as follows:

  • In fact, it means[]change into{}Just fine.
  • SetandListThe two biggest differences are:SetIs unordered, and the elements are not repeated.
//Definition of set
//1. Use type derivation definition
var lettersSet = {'a', 'b', 'c', 'd'};
print('$lettersSet ${lettersSet.runtimeType}');

//2. Clearly specify the type
Set<int> numbersSet = {1, 2, 3, 4};
print('$numbersSet ${numbersSet.runtimeType}');

Last,MapIt is a dictionary type that we often say. Its definition is as follows:

//Definition of map
//1. Use type derivation definition
var infoMap1 = {'name': 'why', 'age': 18};
print('$infoMap1 ${infoMap1.runtimeType}');

//2. Clearly specify the type
Map < string, Object > infomap2 = {'height': 1.88, 'address':' Beijing '};
print('$infoMap2 ${infoMap2.runtimeType}');

4.4.2. Common operations of set

Now that we understand how these three sets are defined, let’s look at some of the most basic common operations

The first type is the property that all collections support to get the lengthlength

//Get the length of the collection

The second type is add / delete / include operation

  • And yes.ListBecause the elements are ordered, it also provides a way to delete the elements at the specified index location
//Add / remove / include elements
print('$numbers $numbersSet');

print('$numbers $numbersSet');


//List delete elements according to index

The third category isMapOperation

  • Because it has key and value, it should be clear whether it is based on key, value or key / value pair whether it is reading value or operation.
//Map operation
//1. Get value according to key
print(infoMap1['name']); // why

//2. Get all entries
print('${infoMap1.entries} ${infoMap1.entries.runtimeType}'); // (MapEntry(name: why), MapEntry(age: 18)) MappedIterable<String, MapEntry<String, Object>>

//3. Get all keys
print('${infoMap1.keys} ${infoMap1.keys.runtimeType}'); // (name, age) _CompactIterable<String>

//4. Get all values
print('${infoMap1.values} ${infoMap1.values.runtimeType}'); // (why, 18) _CompactIterable<Object>

//5. Judge whether a key or value is included
print('${infoMap1.containsKey('age')} ${infoMap1.containsValue(18)}'); // true true

//6. Delete elements according to key
print('${infoMap1}'); // {name: why}

Five. Function

5.1. Basic definition of function

Dart is a real object-oriented language, so even if a function is an object, there are all types. Type is function.

This means that a function can be defined as a variable, as an argument to another function, or as a return value

How to define a function:

Return value function name (parameter list){
  Function body
  Return return value

According to the above definition, we define a complete function:

int sum(num num1, num num2) {
  return num1 + num2;

Effective dart recommends using type annotation for public APIs, but if we omit the type, it still works

sum(num1, num2) {
  return num1 + num2;

In addition, if there is only one expression in a function, you can use arrow syntax(arrow syntax)

  • Note that it can only be an expression, not a statement
sum(num1, num2) => num1 + num2;

5.2. Parameter problem of function

The parameters of a function can be divided into two categories: required and optional

All the parameters used before are required

5.2.1. Optional parameters

Optional parameters can be divided intoName optional parametersandLocation optional parameters

Definition method:

Name optional parameters: {Param1, param2,...}
Location optional parameters: [Param1, param2,...]

Demonstration of naming optional parameters:

//Name optional parameters
printInfo1(String name, {int age, double height}) {
  print('name=$name age=$age height=$height');

//Call printinfo1 function
printInfo1('why'); // name=why age=null height=null
printInfo1('why', age: 18); // name=why age=18 height=null
printInfo1('why', age: 18, height: 1.88); // name=why age=18 height=1.88
printInfo1('why', height: 1.88); // name=why age=null height=1.88

Demonstration of location optional parameters:

//Define location optional parameters
printInfo2(String name, [int age, double height]) {
  print('name=$name age=$age height=$height');

//Call printinfo2 function
printInfo2('why'); // name=why age=null height=null
printInfo2('why', 18); // name=why age=18 height=null
printInfo2('why', 18, 1.88); // name=why age=18 height=1.88

Name optional parameters. You can specify that a parameter must be passed (use @ required, there is a problem)

//Required for naming optional parameters
printInfo3(String name, {int age, double height, @required String address}) {
  print('name=$name age=$age height=$height address=$address');

5.2.2. Parameter default value

Parameters can have default values, which are used without passing in

  • Note that only optional parameters can have default values, and required parameters cannot have default values
//Default value of parameter
printInfo4(String name, {int age = 18, double height=1.88}) {
  print('name=$name age=$age height=$height');

The main function in dart accepts optional list parameters as parameters, so when using the main function, we can pass in parameters or not

5.3. Functions are first class citizens

In many languages, functions cannot be used as first-class citizens, such as Java / OC. This limitation makes programming not flexible enough, so modern programming languages basically support functions as first-class citizens, and dart also supports them

This means that you can assign a function to a variable or use it as a parameter or return value of another function

main(List<String> args) {
  //1. Assign a function to a variable
  var bar = foo;

  //2. Take the function as the parameter of another function

  //3. Use the function as the return value of another function
  var func =getFunc();

//1. Define a function
foo(String name) {
  Print ('incoming Name: $name ');

//2. Take the function as the parameter of another function
test(Function func) {

//3. Use the function as the return value of another function
getFunc() {
  return foo;

5.4. Use of anonymous functions

Most of the functions we define will have their own names, such as Foo and test functions defined earlier.

But in some cases, it’s too much trouble to name a function. We can use a function without a name, which can be called an anonymous function(anonymous function), orlambdaperhapsclosure

main(List<String> args) {
  //1. Define array
  Var movies = ['inception', 'interstellar crossing', 'juvenile school', 'big talk journey to the West'];

  //2. Use foreach to traverse: named function
  printElement(item) {

  //3. Use foreach to traverse: anonymous function
  movies.forEach((item) {
  movies.forEach((item) => print(item));

5.5. Lexical scope

The morphology in dart has its own scope, which is determined by the structure of the code ({})

The variables in their scope are used first. If they are not found, they will be searched out layer by layer.

var name = 'global';
main(List<String> args) {
  // var name = 'main';
  void foo() {
    // var name = 'foo';


5.6. Lexical closure

Closures can access lexical – scoped variables, even if the function is used elsewhere.

main(List<String> args) {
  makeAdder(num addBy) {
    return (num i) {
      return i + addBy;

  var adder2 = makeAdder(2);
  print(adder2(10)); // 12
  print(adder2(6)); // 8

  var adder5 = makeAdder(5);
  print(adder5(10)); // 15
  print(adder5(6)); // 11

5.7. Return value problem

All functions return a value. If no return value is specified, the statement returns NULL; it is implicitly attached to the function body.

main(List<String> args) {
  print(foo()); // null

foo() {
  print('foo function');

Note: all contents start with the official account. After that, Flutter will update other technical articles. TypeScript, React, Node, uniapp, mpvue, data structure and algorithm will also update some of their learning experiences. Welcome everyone’s attention.

Dart (1)