I will update a series of Flutter text tutorials in the coming days
Update progress: at least two articles per week;
Update location: first in the public account, the next day update in nuggets, Sifu and other places;
More communication: You can add me on wechat at 372623326 and follow me on Weibo at CoderWhy
I hope you can help forward, click to see, give me more creative power.
Years later, you will find that choosing the wrong company and industry will cost you far more than choosing the wrong language.
And the computer industry, only one programming language is obviously not realistic, receive a new language, not as difficult as you imagine!
Dart Introduction and installation
1.1 know the Dart
Dart is a given that Google has chosen Dart for Flutter. No matter how much you want to develop Flutter in languages you are familiar with, such as JavaScript, Java, Swift, C++, etc., at least not yet.
As I walk through Dart, I’ll assume that you already have some background in programming languages, such as JavaScript, Java, Python, C++, etc.
In fact, if you’re confident in the language, the Dart learning process can be ignored:
- Because after you learn N programming languages, you will discover them
The difference is not huge
; - does
Grammatical differences
+Certain languages have certain features
Some languages don’t have certain features; - When I first came into contact with Flutter, I did not specifically look at Dart’s grammar. Instead, I went back to understand some of the grammar when I was not familiar with it.
So, if you know enough about programming languages, you can skip our next Dart lesson:
- I’m not going to list all the features, I’m going to highlight the most important language features;
- Some of the properties of Flutter may be explained separately when we explain some of Flutter later;
Let’s start by installing Dart!
1.2. Install the Dart
Why do YOU need to install Dart?
Dart is already built into the Flutter SDK when it is installed. Dart can be written and run using Flutter directly.
However, if you want to learn Dart on your own and run your own Dart code, it’s best to install a Dart SDK.
Download the Dart SDK
Go to the Dart official website and download the Dart for your operating system
- Official website: dart.dev/get-dart
No matter what the operating system, there are two ways to install: through the tool installation or directly download SDK, configure environment variables
1. Install using a tool
- Windows is available through Chocolatey
- MacOS is available through Homebrew
- There are detailed explanations on the official website for installation and operation
2. Download the SDK and configure environment variables
- Dart.dev /tools/ SDK /a…
- I used this setup.
- After the download is complete, configure environment variables according to the path.
1.3. VSCode configuration
In learning Dart, I used VSCode as the editor
- On the one hand, it’s very easy to write code, and I like the interface style
- On the other hand, I can quickly see the effect of my code on the terminal
Dart writing with VSCode requires installing the Dart plug-in: I have installed four plug-ins for VSCode so far
- Dart and the Flutter plugin are for Flutter development
- Atom One Dark Theme is One of my personal favorites
- Code Runner can click the button in the upper right corner to let me run the Code quickly
2. Hello Dart
2.1. Hello World
Now, it’s time to get down to business. Learn a programming language, starting with the heirloom Hello World.
Create a new helloworld.dart file in VSCode and add the following:
main(List<String> args) {
print('Hello World');
}
Copy the code
Dart helloWorld.dart is executed on the terminal and you can see the result of Hello World.
Once you’ve done this, how much information do you get from your previous programming language?
2.2. Analysis of procedures
Here’s my own summary:
- The Dart language entry is also the main function and must be explicitly defined.
- Dart entry function
main
There is no return value; - Three, pass to
main
The command line argument is passedList<String>
The finished.- You can understand it from the literal value
List
Is a collection type in Dart. - Every single one of them
String
Both mean pass tomain
A parameter to;
- You can understand it from the literal value
- When defining a string, you can use single or double quotation marks.
- 5. Each line must end with a semicolon. Many languages do not require semicolons, such as Swift and JavaScript.
Define variables
3.1. Explicit (Explicit)
How to declare a variable explicitly, in the following format:
Variable type Variable name = assignment;Copy the code
Sample code:
String name = 'coderwhy';
int age = 18;
double height = 1.88;
print('${name}.${age}.${height}'); // The stitching method will be explained later
Copy the code
Note: A defined variable can change its value, but it cannot be assigned to another type
String content = 'Hello Dart';
content = 'Hello World'; / / correct
content = 111; // Assign an int to a String variable
Copy the code
3.2. Type Inference
A type derivation declares a variable in the following format:
var/dynamic/const/finalVariable name = assignment;Copy the code
3.3.1. Use of var
An example of how to use var:
- RuntimeType is used to get the current type of a variable
var name = 'coderwhy';
name = 'kobe';
print(name.runtimeType); // String
Copy the code
Incorrect use of var:
var age = 18;
age = 'why'; // You cannot assign a String to an int
Copy the code
3.3.2. Use of dynamic
If you really want to do this, you can use dynamic to declare variables:
- In development, however, dynamic is usually not used because of the potential dangers of typed variables
dynamic name = 'coderwhy';
print(name.runtimeType); // String
name = 18;
print(name.runtimeType); // int
Copy the code
3.3.3. Use of Final&const
Both final and const are used to define constants, meaning that values cannot be changed after they are defined
final name = 'coderwhy';
name = 'kobe'; // Error
const age = 18;
age = 20; // Error
Copy the code
What’s the difference between final and const?
- When const is assigned, the assignment must be determined at compile time
- Final can be retrieved dynamically when assigning, for example to a function
String getName() {
return 'coderwhy';
}
main(List<String> args) {
const name = getName(); // Error because the function needs to be executed to get the value
final name = getName(); // The right thing to do
}
Copy the code
Final and const
- First, const cannot be assigned to datetime.now ()
- Second, final, once assigned, has a definite result and will not be assigned again
// const time = DateTime.now(); // Wrong assignment
final time = DateTime.now();
print(time); / / the 09:02:54 2019-04-05. 052626
sleep(Duration(seconds: 2));
print(time); / / the 09:02:54 2019-04-05. 052626
Copy the code
Const is placed to the right of assignment statements to share objects and improve performance:
- This is for now, and I’ll come back to it later when I talk about constant constructors for 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
}
Copy the code
4. Data types
4.1. Numeric types
For values, we don’t have to worry about signs, the width of the data, the accuracy of the data, etc. Just remember to use int for integers and double for floating-point numbers.
However, it is important to note that the range of ints and doubles represented in Dart 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. Float type double
double height = 1.88;
print(height);
Copy the code
Conversion between strings and numbers:
// String and number conversion
// 1. Convert the string to a 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
Copy the code
4.2. Boolean types
Dart provides a bool of the Boolean type, true and false
// Boolean type
var isFlag = true;
print('$isFlag ${isFlag.runtimeType}');
Copy the code
Note: Dart does not judge that non-zero is true, or that non-null is true
Dart’s type-safety means you can’t use code like IF (non-BooleanValue) or Assert (non-BooleanValue).
var message = 'Hello Dart';
// This is not the case
if (message) {
print(message)
}
Copy the code
4.3. String type
The Dart string is a sequence of UTF-16 encoding units. You can create a string using single or double quotation marks:
// 1. How to define a string
var s1 = 'Hello World';
var s2 = "Hello Dart";
var s3 = 'Hello\'Fullter';
var s4 = "Hello'Fullter";
Copy the code
You can use three single or double quotation marks to indicate a multi-line string:
// 2. The way to represent multi-line strings
var message1 = "Ha ha ha ha ha ha ha ha ha ha ha ha ha;
Copy the code
Concatenation of strings with other variables or expressions: Use ${expression}, {} can be omitted if the expression is an identifier
// 3. Splice other variables
var name = 'coderwhy';
var age = 18;
var height = 1.88;
print('my name is ${name}, age is $age, height is $height');
Copy the code
4.4. Collection types
4.4.1. Definition of collection types
Dart has three of the most common collection types built in: List/Set/Map.
Where, List can be defined as:
/ / the List definition
// 1. Use type derivation for definitions
var letters = ['a'.'b'.'c'.'d'];
print('$letters ${letters.runtimeType}');
// 2. Specify the type explicitly
List<int> numbers = [1.2.3.4];
print('$numbers ${numbers.runtimeType}');
Copy the code
Where, set can be defined like this:
- In fact, that is to say
[]
Switch to{}
It’ll be ok. Set
andList
The two biggest differences are:Set
Is unordered and the elements are not repeated.
// Set definition
// 1. Use type derivation for definitions
var lettersSet = {'a'.'b'.'c'.'d'};
print('$lettersSet ${lettersSet.runtimeType}');
// 2. Specify the type explicitly
Set<int> numbersSet = {1.2.3.4};
print('$numbersSet ${numbersSet.runtimeType}');
Copy the code
Finally, Map is what we call a dictionary type, which is defined like this:
// Map definition
// 1. Use type derivation for definitions
var infoMap1 = {'name': 'why'.'age': 18};
print('$infoMap1 ${infoMap1.runtimeType}');
// 2. Specify the type explicitly
Map<String.Object> infoMap2 = {'height': 1.88.'address': 'Beijing'};
print('$infoMap2 ${infoMap2.runtimeType}');
Copy the code
4.4.2. Common operations for collections
Now that we know how these three collections are defined, let’s look at some of the most basic common operations
The first type is length, which is supported by all collections:
// Get the length of the set
print(letters.length);
print(lettersSet.length);
print(infoMap1.length);
Copy the code
The second type is add/delete/include operations
- And, for
List
Since the elements are ordered, it also provides a method to delete the elements at the specified index position
// 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 deletes elements according to index
numbers.removeAt(3);
print('$numbers');
Copy the code
The third type is Map operations
- Since it has a key and a value, it is important to make it clear whether the read value or the operation is based on key, value, or key/value pairs.
// Map operation
// 1. Obtain value based on 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. Check whether a key or value is included
print('${infoMap1.containsKey('age')} ${infoMap1.containsValue(18)}'); // true true
// 6. Delete elements based on key
infoMap1.remove('age');
print('${infoMap1}'); // {name: why}
Copy the code
Function of 5.
5.1. Basic definition of functions
Dart is a true object-oriented language, so even though functions are objects, they have types, and the types are functions.
This means that functions can be defined as variables or as arguments or return values to other functions.
Function definition:
Return value The name of the function (argument list) {function bodyreturnThe return value}Copy the code
As defined above, we define a complete function:
int sum(num num1, num num2) {
return num1 + num2;
}
Copy the code
Effective Dart suggests using type annotations for public apis, but it still works if we omit the type
sum(num1, num2) {
return num1 + num2;
}
Copy the code
Alternatively, if there is only one expression in the function, arrow syntax can be used.
- Note that this is only an expression, not a statement
sum(num1, num2) => num1 + num2;
Copy the code
5.2. Parameters of functions
The parameters of a function can be divided into two categories: required and optional
The previous parameters are required.
5.2.1. This parameter is optional
Optional parameters can be classified into named optional parameters and location optional parameters
Definition method:
Name Optional parameters: {param1, param2... } Position Optional parameters: [param1, param2,...]Copy the code
A demonstration of naming optional arguments:
// Naming is optional
printInfo1(String name, {int age, double height}) {
print('name=$name age=$age height=$height');
}
// Call printInfo1
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 = according to the age 18 height = = 1.88
printInfo1('why', height: 1.88); / / name = according to the age = null height = 1.88
Copy the code
Demonstration of position optional parameters:
This parameter is optional
printInfo2(String name, [int age, double height]) {
print('name=$name age=$age height=$height');
}
// Call printInfo2
printInfo2('why'); // name=why age=null height=null
printInfo2('why'.18); // name=why age=18 height=null
printInfo2('why'.18.1.88); / / name = according to the age 18 height = = 1.88
Copy the code
Name optional arguments to specify that a parameter is required (using @required, problematic)
// Name the optional parameter must
printInfo3(String name, {int age, double height, @required String address}) {
print('name=$name age=$age height=$height address=$address');
}
Copy the code
5.2.2. Parameter Default values
Arguments can have default values, which are used if not passed in
- Note that only optional parameters can have default values. Mandatory 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');
}
Copy the code
Dart’s main function is one that takes an optional list parameter, so we may or may not pass the parameter when using main
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 less flexible, so modern programming languages generally support functions as first-class citizens, as Dart does.
This means that you can assign a function to a variable, or use a function as an argument or return value to another function.
main(List<String> args) {
// 1. Assign function to a variable
var bar = foo;
print(bar);
// 2. Take a function as an argument to another function
test(foo);
// 3. Use the function as the return value of another function
var func =getFunc();
func('kobe');
}
1. Define a function
foo(String name) {
print('Name passed in:$name');
}
// 2. Take a function as an argument to another function
test(Function func) {
func('coderwhy');
}
// 3. Use the function as the return value of another function
getFunc() {
return foo;
}
Copy the code
5.4. Use of anonymous functions
Most of the functions we define have names, such as foo, test, and so on.
In some cases, however, naming a function is too cumbersome. Instead, we can use a function without a name, which can be called anonymous function, lambda or closure.
main(List<String> args) {
// 1. Define arrays
var movies = [Inception.'Interstellar'.Life of PI.A Chinese Odyssey];
// 2. Use forEach to traverse: named functions
printElement(item) {
print(item);
}
movies.forEach(printElement);
// 3. Use forEach to traverse: anonymous function
movies.forEach((item) {
print(item);
});
movies.forEach((item) => print(item));
}
Copy the code
5.5. Lexical scope
The morphology in DART has its own explicit scope, which is determined by the structure of the code ({})
Use variables in your scope first, and if none are found, layer by layer.
var name = 'global';
main(List<String> args) {
// var name = 'main';
void foo() {
// var name = 'foo';
print(name);
}
foo();
}
Copy the code
5.6. Lexical closures
Closures can access variables within their lexical scope, 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
}
Copy the code
5.7. Return value problem
All functions return a value. If no return value is specified, the statement returns NULL; Implicitly attached to the function body.
main(List<String> args) {
print(foo()); // null
}
foo() {
print('foo function');
}
Copy the code
Note: All content will be published on our official website. Later, Flutter will also update other technical articles, including TypeScript, React, Node, Uniapp, MPvue, data structures and algorithms, etc. We will also update some of our own learning experiences