Flutter (3): Dart (1)

Time:2021-2-24

Preface 1: I will update some flutter text tutorials in the next period of time

Update progress:At least two articles a 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 microblog: coderwhy

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

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

And the computer industry, only a programming language is obviously unrealistic, to receive a new language, and not as difficult as you imagine!

1、 Introduction and installation of dart

1.1. Meet dart

It’s an established fact that Google has chosen dart for flutter. No matter how much you want to develop flutter with familiar languages, such as JavaScript, Java, swift, C + +, at least for now.

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

In fact, if you’re interested in programming languagesEnough confidenceDART’s learning process can even be directly ignored

  • Because after you’ve learned n programming languages, you’ll find themThe difference is not big
  • It’s justGrammatical differences+Some languages have certain characteristicsSome languages have no characteristics;
  • When I first came into contact with flutter, I didn’t specially look at DART’s grammar, but went back to understand some grammar when I was not very proficient;

So, if you know enough about programming languages, 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 explaining some knowledge of flutter later;

Now, let’s start by installing dart!

1.2. Install dart

Why do I need to install dart?

In fact, dart has been built in when installing the flutter SDK. We can use flutter to write and run dart directly.

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

Download dart SDK

Go to dart’s official website and download corresponding darts according to different operating systems

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

1. Installation by tools

  • Windows can use chocolate
  • Mac OS can be accessed through homebrew
  • Specific installation operation, the official website has a detailed explanation

2. Download SDK directly and configure environment variables

1.3. Vscode configuration

In learning dart, I useVSCodeAs 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 in the terminal

Writing dart with vscode requires installing dart plug-ins: I have installed four plug-ins for this vscode

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

Flutter (3): Dart (1)

2、 Hello dart

2.1. Hello World

Next, you can get to the point. Learning programming languages starts with the ancestral Hello world.

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

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

Then it is executed on the terminaldart helloWorld.dartAnd you can see thatHello WorldIt’s a good result.

How much information can you get from the programming language you learned before?

2.2. Program analysis

Next is my own summary

  • 1、 The entry of dart language is also the main function, which must be displayed and defined;
  • 2、 The entry function of dartmainThere is no return value;
  • 3、 Pass on tomainThe command line parameters of theList<String>It’s done.

    • It’s understandable from the literal valueListIs a collection type in dart.
    • Each of themStringAll means to pass on tomainA parameter of the;
  • 4、 When defining strings, you can use single quotation marks or double quotation marks;
  • 5、 A semicolon must be used at the end of each line of statement. Many languages do not need semicolons, such as swift and JavaScript;

3、 Defining variables

3.1. Explicit

The way to explicitly declare variables 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

Type derivation 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 usage of VaR:

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

3.3.2. Use of dynamic

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

  • But in development, dynamic is usually not used, because variable of type will 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 to say, the values cannot be modified after definition

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

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

What’s the difference between final and const?

  • When const is assigning a value, the content of the assignment must be determined during compilation
  • Final can be obtained dynamically during assignment, such as assigning a function
String getName() {
  return 'coderwhy';
}

main(List<String> args) {
  Const name = getname(); // this is an error, because you need to execute the function to get the value
  Final name = getname(); // correct approach
}

Small cases of final and const:

  • First of all, const cannot be assigned to DateTime.now ()
  • Secondly, once final is assigned, there will be a definite result and it 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

  • You can understand it for a while. I will refer to this concept again when I explain the constant constructor of a class later
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 need to care about whether it has sign or not, as well as the width and accuracy of data. Just remember to use integersintFor floating point numbersdoubleThat’s it.

But, to be clear, it’s in dartintanddoubleThe scope of representability is not fixed, it depends on the platform on which dart is running.

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

//2. Floating point type double
double height = 1.88;
print(height);

Conversion between string and number:

//String and number conversion
//1. String to digit
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. Converting numbers to strings
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 boolean type, dart provides a bool type with values of true and false

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

Note: dart cannot judge whether non-zero is true or whether non empty is true

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

var message = 'Hello Dart';
  //Wrong way of writing
  if (message) {
    print(message)
  }

4.3. String type

The dart string is a sequence of utf-16 encoding units. You can use single or double quotation marks 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 quotation marks to represent a multiline string:

//2. How to represent multiline string
var message1 = '''
Ha ha ha
Interesting
Hey, hey, hey '';

String and other variables or expression splicing: use ${expression}, if the expression is an identifier, {} can be omitted

//3. 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:

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

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

Among them,setIt can be defined as:

  • In fact, that is to say[]change into{}Just fine.
  • SetandListThe two biggest differences are:SetIt’s unordered, and the elements don’t repeat.
//Definition of set
//1. Use type to deduce definition
var lettersSet = {'a', 'b', 'c', 'd'};
print('$lettersSet ${lettersSet.runtimeType}');

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

last,MapIt is a dictionary type that we often talk about

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

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

4.4.2. Common operations of set

After understanding how these three sets are defined, let’s look at some of the most basic common operations

The first type is the attribute that all sets support to get the lengthlength

//Gets the length of the collection
print(letters.length);
print(lettersSet.length);
print(infoMap1.length);

The second type is the add / delete / include operation

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

numbers.remove(1);
numbersSet.remove(1);
print('$numbers $numbersSet');

print(numbers.contains(2));
print(numbersSet.contains(2));

//List delete elements according to index
numbers.removeAt(3);
print('$numbers');

The third category isMapOperation of

  • Because it has a key and a value, whether it is reading a value or operating, it should be clear whether it is based on a key, a value, or a key / value pair.
//Map operation
//1. Get the value according to the 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 the keys
print('${infoMap1.keys} ${infoMap1.keys.runtimeType}'); // (name, age) _CompactIterable<String>

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

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

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

5、 Function

5.1. Basic definition of function

Dart is a real object-oriented language, so even if a function is an object, all functions have types, and the type is function.

This means that functions can be defined as variables or as parameters or return values of other functions

Function definition method:

Returns the name of the value function (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 annotations for public APIs, but if we omit types, they still work

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

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

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

5.2. Parameter problem of function

Function arguments can be divided into two categories: required arguments and optional arguments

The parameters used before are required

5.2.1. Optional parameters

The 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');
}

//Calling the 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');
}

//Calling the 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 the optional parameter. You can specify that a parameter is required (use @ required, there is a problem)

//Must name 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 when they are not passed in

  • Note that only optional parameters can have default values, and required parameters cannot have default values
//The default value of the 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 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 restriction makes programming inflexible. Therefore, 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;
  print(bar);

  //2. Take the function as the parameter of another function
  test(foo);

  //3. Take the function as the return value of another function
  var func =getFunc();
  func('kobe');
}

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

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

//3. Take 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 cumbersome to name functions. We can use functions without names, which can be called anonymous functions(anonymous function)It can also be calledlambdaperhapsclosure

main(List<String> args) {
  //1. Define array
  Var movies = ['inception ','star Trek','youth school ','talk about the journey to the West'];

  //2. Use foreach to traverse: functions with names
  printElement(item) {
    print(item);
  }
  movies.forEach(printElement);

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

5.5. Lexical scope

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

Give priority to the variables in your own scope, and if not found, look them out layer by layer.

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

  foo();
}

5.6. Lexical closure

Closures can access variables within their lexical scope, even if functions are used in other places.

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 body of the function.

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.

Flutter (3): Dart (1)