Flutter Solves Dart

Preface 1: I will update some Flutter text tutorials in the next few days.

Update progress: at least two articles per week;

Renewal Place: First launched in the public number, the next day updated in the digging, think about whether or not and other places;

More Exchanges: You can add my Weibo 372623326, pay attention to my Weibo: coderwhy

I hope you can help me forward, click and see, give me more creative power.

Preface 2: A few years later, you will find that the loss of choosing the wrong company and industry is much greater than the loss of choosing the wrong language.

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

Introduction and installation of Dart

1.1. Understanding Dart

It's already a fact that Google chose Dart for Flutter. No matter how much you want to develop Flutter in familiar languages such as JavaScript, Java, Swift, C++, etc., it's not possible at least for now.

In explaining Dart, I will assume that you already have some programming language foundation, such as JavaScript, Java, Python, C++.

In fact, if you have enough confidence in programming languages, Dart's learning process can even be ignored directly:

  • Because after you have studied N programming languages, you will find that they are not very different.
  • It's nothing more than grammatical differences + some languages have certain characteristics, while some languages do not have some characteristics.
  • When I first came into contact with Flutter, I didn't look at Dart's grammar, but looked back at some grammar when I wasn't 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 linguistic features to explain specifically;
  • Some features may be explained separately when Flutter's knowledge is explained later.

Next, let's start with installing Dart.

1.2. Install Dart

Why do you need to install Dart?

In fact, when installing Flutter SDK, it has built-in Dart, and we can use Flutter directly to write and run Dart.

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 Dart's office, download the corresponding Dart according to different operating systems

No matter what operating system, there are two ways to install it: installing SDK through tools and downloading SDK directly, configuring environment variables

1. Installation by Tools

  • Windows can use Chocolatey
  • macOS can use homebrew
  • Detailed explanations for the specific installation and operation of the official website

2. Download SDK directly and configure environment variables

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

1.3. VSCode configuration

In learning Dart, I used VSCode as an editor

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

Writing Dart with VSCode requires installing Dart plug-ins: 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 lets me run the code quickly by clicking on the button in the upper right corner.

II. Hello Dart

2.1. Hello World

Next, we can get to the point. Learn programming languages, starting with the ancestral Hello World.

Create a new helloWorld.dart file in VSCode and add the following:

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

Then dart Hello World. dart is executed at the terminal, and the result of Hello World can be seen.

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

2.2. Procedure analysis

Next is my own summary:

  • First, the entrance of Dart language is also main function, and it must be defined by display.
  • Second, Dart's entry function main has no return value.
  • 3. The command-line parameters passed to main are accomplished through List < String>.

    • Literally, you can understand that List is the collection type in Dart.
    • Each String represents a parameter passed to main.
  • Fourth, when defining strings, single or double quotation marks can be used.
  • Fifth, every statement must end with a semicolon, many languages do not need a semicolon, such as Swift, JavaScript;

Defining variables

3.1. Explicit statement

The way variables are explicitly declared is as follows:

Variable type variable name = assignment;

Sample code:

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

Note: Defined variables can modify values, but cannot assign other types

String content = 'Hello Dart';
content = 'Hello World'; // Correct
content = 111; // Wrong, assigning 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 var use:

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

The 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 really want to do this, you can use dynamic to declare variables:

  • But in development, dynamic is usually not used because of the potential dangers of type variables.
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, i.e. values after definitions cannot be modified.

final name = 'coderwhy';
name = 'kobe'; // Wrong practices

const age = 18;
age = 20; // Wrong practices

What's the difference between final and const?

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

main(List<String> args) {
  const name = getName(); // The wrong way to do this is to execute the function to get the value
  final name = getName(); // The Right Way
}

final and const small cases:

  • First, const cannot be assigned to DateTime.now()
  • Secondly, once final is assigned, it has a definite result and will not be assigned again
// const time = DateTime.now(); // incorrect assignment
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 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
}

IV. Data Types

4.1. Number type

For numerical values, we don't have to worry about whether they have symbols or not, as well as the width and accuracy of the data. Just remember to use int for integers and double for floating-point numbers.

However, it should be noted that the range of int and double representations in Dart is not fixed, it depends on the platform running Dart.

// 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 strings and numbers:

// 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. Digital String Conversion
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 types, Dart provides a bool type with values of true and false

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

Note: Dart can't judge whether non-zero is true or non-empty is true

Dart's type security means that you can't use code such as if (non-boolean value) or assert (non-boolean value).

  var message = 'Hello Dart';
  // Wrong Writing
  if (message) {
    print(message)
  }

4.3. String type

Dart strings are sequences 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";

Three single or double quotation marks can be used to represent a multi-line string:

// 2. Representation of multi-line strings
var message1 = '''
Ha ha ha
 Interesting
 Hey hey hey'';

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

// 3. Stitching 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. Collection type

4.4.1. Definition of set type

For collection types, Dart built in the three most commonly used types: List / Set / Map.

List can be defined as:

// List Definition
// 1. Derivation of definitions using types
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}');

Where set can be defined as:

  • In fact, that is to say, [] is replaced by {}.
  • The biggest difference between Set and List is that Set is disordered and elements are not duplicated.
// Definition of Set
// 1. Derivation of definitions using types
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}');

Finally, Map is what we often call a dictionary type. Its definition is as follows:

// Definition of Map
// 1. Derivation of definitions using types
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 collections

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

The first category is the attribute length for obtaining length supported by all collections:

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

The second category is add/delete/include operations

  • Moreover, for List, because the elements are ordered, it also provides a way to delete the elements at the specified index location.
// Add/delete/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 deletes elements based on index
numbers.removeAt(3);
print('$numbers');

The third category is Map operations.

  • Because it has key and value, whether it reads or operates, it must be clear that it is based on key, value, or key/value pairs.
// 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. Determine whether a key or value is included
print('${infoMap1.containsKey('age')} ${infoMap1.containsValue(18)}'); // true true

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

V. Functions

5.1. Basic Definitions of Functions

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

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

Definition of function:

Name of return 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 suggests using type annotations for public API s, 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, arrow syntax can be used.

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

5.2. Parametric Problems of Functions

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

The parameters used previously are all required parameters.

5.2.1. Optional parameters

Optional parameters can be divided into named optional parameters and position optional parameters.

Definition:

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 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 optional location parameters:

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

// Call 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 optional parameters, and you can specify that a parameter must be passed on (using @required, problematic)

// Necessary 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. Default values of parameters

Parameters can have default values, using default values without passing in

  • Note that only optional parameters can have default values, and must not have default values.
// Default values of parameters
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 restriction makes programming less flexible, so modern programming languages basically support functions as first-class citizens, 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. Assigning a function to a variable
  var bar = foo;
  print(bar);

  // 2. Taking a function as a parameter of another function
  test(foo);

  // 3. Use a 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. Using a function as a parameter of another function
test(Function func) {
  func('coderwhy');
}

// 3. Use a 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, test functions and so on.

But in some cases, naming functions is too cumbersome. We can use functions without names, which can be called anonymous functions, or lambda or closure.

main(List<String> args) {
  // 1. Define arrays
  var movies = ['Inception', 'Interstellar crossing', 'Juvenile School', 'Talk about the Westward Journey'];

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

  // 3. Use forEach traversal: anonymous functions
  movies.forEach((item) {
    print(item);
  });
  movies.forEach((item) => print(item));
}

5.5. Lexical Scope

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

Priority is given to variables in your scope, and if they are not found, they are searched 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 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; implicitly appended to the body of the function.

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

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

Note: All content will be published on the public number. In addition to Flutter, other technical articles will be updated, such as TypeScript, React, Node, uniapp, mpvue, data structure and algorithm, etc. Some of your own learning experiences will also be updated. Welcome your attention.

Tags: Javascript Programming SDK Java

Posted on Mon, 09 Sep 2019 05:12:54 -0700 by purefusion