The subject catalog of Flutter: this catalog helps you quickly find out what you want to learn!!

Give your users a whole new experience with the beautiful Material Design and Cupertino (iOS style) widgets built into the Flutter, rich Motion API, smooth and natural sliding effects and platform awareness.

But these silky interfaces are also built from line by line Dart code, so it’s important to understand and master Dart syntax

I know you may not read this article in detail ===> if it was me, I would not, who would be so boring to chew on grammar, especially in such a fast-paced era. butThe Dart grammarThis is very important 🎯🎯🎯. I hope you read it briefly, and then click 👍👍. Quick access to 📚📚📚(just like a dictionary)

So let’s start with a little introduction from variables and operators to classes and libraries! For details, please refer to the official Dart documentation:

Ps: Open DartPad is similar to Swift’s Playground

Does it feel very convenient, in fact, our simple grammar test, can use this, simple and clear!! 😸

① The important concept of Dart

  • 🎯 Each variable is an object, and each object is an instance of a class. Even numbers, functions, and null are objects. All objects inherit from the Object class

  • 🎯 specifies a static type (as in the previous example of num) to make the intent clear and use Tools to enable static checking, but it is optional. (You may have noticed that when debugging code, variables without a specified type get a special type: Dynamic)

  • 🎯Dart parses all code before running. You can provide hints to Dart, for example, by using type or compile time constants to catch errors or help code run faster.

  • 🎯Dart supports top-level functions (such as main()) as well as functions in classes or objects (static and instance methods, respectively). You can also create functions (nested or local) within functions.

  • 🎯 Similarly, Dart supports top-level variables, as well as variables that depend on classes or objects (both static and instance variables). Instance variables are sometimes referred to as fields or properties.

  • 🎯 Unlike Java, Dart does not have the keywords public, protected, and private. If an identifier starts with an underscore (_), both it and its library are private. For more information, see Libraries and Visibility.

  • The 🎯 identifier can start with a letter or (_), or a combination of characters and numbers.

  • 🎯 Sometimes it’s important to decide whether it’s an expression or a statement, so we need to know exactly what these two words are.

  • 🎯Dart Tools can report two types of problems: warning ⚠️ and Error ❎. Warnings are just signs that the code may not work properly, but they do not prevent the program from executing. Errors can be compile-time or run-time. Compile-time errors prevent code from executing. A runtime error causes an exception to be thrown when the code executes.

  • 🎯Dart operates in two modes: Production and Checked. We recommend reviewing pattern development and debugging before deploying it to production mode.

  • 🎯Production Mode is a speed-optimized default mode for the Dart program. Production Mode ignores assert statements and static typing.

  • 🎯Checked Mode is a developer-friendly way to help you catch some types of errors at runtime. For example, if you assign a non-number to declare as a NUM variable, then an exception will be thrown in the check mode.

  • 🎯 Programming languages don’t exist in isolation. Dart does, too. It consists of language specifications, virtual machines, libraries, tools, and more:

    • SDK: Contains the SDKDart VM, Dart2JS, Pub, libraries, and tools.
    • Dartium: inlineDart VMChromiumCan be executed directly in the browserThe dart code.
    • Dart2js:DartThe code is compiled toJavaScriptThe tool.
    • Dart Editor: Based onEclipseFull-featured IDE and includes all of the above tools. Support code completion, code navigation, quick correction, refactoring, debugging and other functions.

(2) the keyword

The keyword The keyword The keyword The keyword
abstract 2 else import 2 super
as 2 enum in switch
assert export 2 interface 2 sync 1
async 1 extends is this
await 3 extension 2 library 2 throw
break external 2 mixin 2 true
case factory 2 new try
catch false null typedef 2
class final on 1 var
const finally operator 2 void
continue for part 2 while
covariant 2 Function 2 rethrow with
default get 2 return yield 3
deferred 2 hide 1 set 2   static 2
do if show 1 implements 2
dynamic 2
  • Words with superscript 1 are contextual keywords; they only make sense at certain points. They are valid identifiers everywhere.

  • Words with superscript 2 are built-in identifiers. To simplify the task of porting JavaScript code to Dart, these keywords are valid identifiers in most places, but they cannot be used as class or type names, nor can they be used as import prefixes.

  • The words with superscript 3 are newer, limited reserved words related to the asynchronous support added after Dart 1.0 was released. You cannot use await or yield as an identifier in the body of any function marked async, async*, or sync*.

  • All other words in the table are reserved words and cannot be used as identifiers.

  • Identifiers are names given to elements in a program, such as variables, functions, etc. The rules for identifiers are

Identifiers can include characters and numbers. However, identifiers cannot start with a number.

  • Identifiers cannot contain special symbols except the underscore (_) or dollar sign ($).
  • The identifier cannot be a keyword.
  • They have to be unique
  • Identifiers are case sensitive.
  • The identifier cannot contain Spaces.
Valid identifier Invalid identifier
firstName Var
first_name first name
num1 first-name
$result 1number

③ Dart is object-oriented

Dart is an object-oriented language. Object-oriented is a software development paradigm that follows real-world modeling. Object Orientation treats programs as collections of objects that communicate with each other through mechanisms called methods.

A: object

Object – An object is a real-time representation of any entity. According to Grady Brooch, each object must have three functions

  • State – is described by the properties of the object.
  • Behavior – Describes how an object behaves.
  • Identity – a unique value that distinguishes an object from a set of objects like this.

class

Classes – The classes of OOP aspects are blueprints for creating objects. A class encapsulates the data of an object.

methods

Methods – Methods facilitate communication between objects.

// Main entry function
void main() {
  // Object oriented
  KCClass cls = new KCClass();
  cls.sayHello();
}

class KCClass{
  void sayHello(){
    print('Hello Dart'); }}Copy the code

④ Variables & constants

1: variable

Let’s start by initializing a variable: name is very simple, and it doesn’t have much to do with iOS and Android development

// Initialize the variable declaration
void varibleFunc(){
  var name = 'cooci';
  dynamic nickName = 'KC';
  Object person = 'cool C';

  // Show the type the declaration will be inferred from. You can use String to show the type of the declaration
  String company = 'LG' ;
  print('i am: $name.$nickName.$person ,$company');
}
Copy the code

Variables store references. The variable named name contains a reference to a string object with a value of “cooci”.

The type of the name variable is inferred to be String, and variables that declare no static type are implicitly declared dynamic. You can also use the dynamic keyword instead of the var keyword to declare variables. Refer to the Design Guidelines to specify Object or dynamic.

To show the type the declaration will be inferred from, you can use String to show the type of the declaration

2: the default value

Uninitialized variables have an initial value of NULL. Even if the numeric type variable is originally null, because the number is an object.

  / / the default value
  int age;
  assert(age == null);
  print(age); // Print null to prove that the numeric type initialization value is NULL
Copy the code

3: Final and const

If you never intend to change a variable, you can use final or const instead of var or add it outside the type. Final variables can only be set once; Const variables are compile-time constants. (Const variables are implicitly final.) The final top-level or class variable is initialized the first time it is used.

// Final and const

 // Final and const
  final student = 'JZ';
  final String studentName = Vibration 'home';
  print('student = ,${[student,studentName]}');

  // A variable that is final or const cannot be modified.
  // student = 'chen'; // a final variable, can only be set once
  const teacher = 'Kody';
  // Constant variables can't be assigned a value
  // teacher = 'Cat';

  // Flnal or const cannot be used with var
  // Members can't be declared to be both 'const' and 'var'
  // const var String teacherName = 'CC';
  // final var String teacherName = 'hank';
  
// If a constant is class-level, use static const
  static const String lector = 'sky';
Copy the code

In fact, here with our usual development cognition is the same! So you can walk through it a little bit.

⑤ Built-in Types

Dart language has special support for the following types:

  • 🎯 Numbers
  • 🎯 strings
  • 🎯 booleans
  • 🎯lists (also known as arrays)
  • 🎯 sets.
  • 🎯 maps
  • 🎯 Runes (for Expressing Unicode Characters in a string)
  • 🎯 symbols

You can use literals to initialize any of these special types. For example, ‘this is a string’ is a string literal, while true is a Boolean literal.

Because each variable in Dart points to an object (an instance of a class), you can usually initialize variables using constructors. Some built-in types have their own constructors. For example, you can use the Map() constructor to create a Map.

A: num type

There are two Dart num types: int + double

// About the num type test
void numFunc() {
  int a = 1;
  print(a);

  double b = 1.12;
  print(b);

// String -> int
  int one = int.parse('1');
3 / / output
  print(one + 2);

// String -> double
  var onePointOne = double.parse('1.1');
/ / output 3.1
  print(onePointOne + 2);

// int -> String
  String oneAsString = 1.toString();
// The argument type 'int' can't be assigned to the parameter type 'String'
//print(oneAsString + 2);
// Output 1 + 2
  print('$oneAsString+ 2 ');
// Output 1 2
  print('$oneAsString2 ');

// double -> String; // double -> String
  String piAsString = 3.14159.toStringAsFixed(2);
// Cut off two decimal places, output 3.14
  print(piAsString);

  String aString = 1.12618.toStringAsFixed(2);
// Check to see if it is rounded and output 1.13
  print(aString);
}
Copy the code

These are generally similar,iOS development note: the type of direct conversion of code!

B: type of Strings

  • Dart strings are sequences of UTF-16 encoding units. You can use single or double quotes to create strings:

  • You can concatenate strings directly with adjacent string words or with the + operator:

  • Another way to create a multi-line string is to use triple quotes with single or double quotes:

  • Use quotes nested within single or double quotes.

  • Use {} to evaluate the value of a variable in a string. Note that ${expression} is required for an expression.

// About string tests
void stringFunc() {
  // the 'Dart string' is a sequence of UTF-16 encoding units. You can create strings using 'single' or 'double' quotes:
  var s1 = 'Study in harmony, without haste and impatience';
  var s2 = "It is better to chase after the wind than to wait for the wind. There is always someone who will come to you in the right season of scenery and understand all your good!!";
  var s3 = 'I am Cooci';
  var s4 = 'cooci';

  assert( '$s3'= ='I am' + 'Cooci');
  assert( '${s4.toUpperCase()}'= ='COOCI');

  // We can concatenate strings directly with adjacent string words or with the '+ operator' :
  var s5 = 'LG_''Cooci_'"Harmonious learning without haste and impatience.";
  assert(s5 ==
      'LG_Cooci_ Harmonious learning without haste and impatience ');

  var s6 = 'LG_' + 'Cooci';
  assert(s6 == 'LG_Cooci');

  // Another way to create a multi-line string is: 'Use triple quotes with single or double quotes:'
  var s7 = Create a multi-line string with single quotation marks;
  var s8 = """ Double quotes to create a multi-line string just make sure it's all lines. """;
  print(s7);
  print(s8);

  // Use quotes nested within single or double quotes.
  ${expression} = ${expression} = ${expression}

  // Single quotes nested with double quotes
  String s9 = '$s1 a "LG" ${s3}';
  // Output harmonious learning, not anxious not impetuous a "LG" I am Cooci
  print(s9);
  // Double quotes nested within single quotes
  String s10 = "${s4.toUpperCase()} abc 'LG' $s4.toUpperCase()";
  // Output COOCI ABC 'aaa' cooci.toupperCase (),
  // We can see that '$s4.toupperCase ()' does not add '{}', so the output is' cooci.toupperCase ()'
  print(s10);
}
Copy the code

C: Bool type

To represent Boolean values, Dart has a type called bool. Only two objects have a bool type: the Boolean literals true and false, both of which are compile-time constants. Because it’s consistent with our general understanding we’re not going to do it

D: Lists the types

The array collection type is more widely applicable! Lists in Dart are relatively simple compared with OC. The key is also in the increase, delete and check, details, please refer to 👇 code


// Lists type test
void listsFunc(){
  // Dart extrapolate list type = list 
      
  // If you try to add a non-integer object to this list, the profiler or runtime will raise an error
  var list = [1.2.3];
  // To create a list of compile-time constants, add const before the list literal:
  var constantList = const [1.2.3];
  // constantList[1] = 1; / / an error

  // spread operator (...) The use of the
  var list1 = [1.2.3];
  var list2 = [0. list1];print(list2);  // [0, 1, 2, 3]
  // Note that if the insert is null, then '(... ?). `
  var list3 ;
  var list4 = [0. ? list3];print(list4);  / / [0]

  // Add, delete, and modify the list
  var list5 = [1.2.3];
  list5.add(4); print(list5);       // [1, 2, 3, 4]
  // Delete the element
  list5.remove(4); print(list5);    / / [1, 2, 3]
  list5.removeAt(0); print(list5);  / / [2, 3]
  // Modify the element
  list5[1] = 100; print(list5);     / / [2, 100]
  / / query
  print(list5.indexOf(2));          / / 0
  print(list5.elementAt(1));        / / 100
  print(list5.contains(Awesome!));       // false
}
Copy the code

Here to make a table for you to quickly look up learning, code you can knock, if there is no time can also do not knock (relatively simple 😆)

operation code meaning The output
Initialize the var list5 = [1, 2, 3] Initializes an array:list5There are three of themintType of elements:1, 2, 3 [1, 2, 3]
new list5.add(4) Add an element at the end:4 [1, 2, 3, 4]
remove list5.remove(4) Remove elements:4 [1, 2, 3]
Modify the list5[1] = 100 The subscript for1Is modified to100 [1, 100, 3]
The query list5.elementAt(2) The query is in the subscript:2The elements of the 100
judge list5.contains(666) To determine if there is666The element false

E: Sets type

Sets are unordered collections, and are used in much the same way as in other languages

// Sets type test
void setsFunc(){
  var names = <String> {};// 或者 Set<String> names = {};
  // ⚠️ var names = {}; // Create a map, not a set.
  names.add('teachers');
  print(names);            // {teachers}
  var persons = {'hank'.'cooci'.'kody'.'cc'.'cat'};
  names.addAll(persons);
  print('$names.${names.length}'); // {teachers, hank, cooci, kody, cc, cat}, 6
}
Copy the code

F: the type of Maps

A map is an object that associates keys and values (what we call a dictionary)

  • mapIs unique in the key-value pair
  • mapThe inside of thevalueCan be the same
  • mapThe inside of thevalueCan be an empty string
  • mapThe inside of thevalueCan I do fornull
// Maps type test
void mapsFunc(){
  var person = {
    // Key: Value
    'age': 18.'name': 'cooci'.'hobby': 'woman'.'height': 1.85
  };
  print(person); // {age: 18, name: cooci, female, height: 1.85}
  print('${person.keys}.${person.values}'); // (age, name, hobby, height),(18, Cooci, female, 1.85)

  // Map assignment, with Key in brackets, not an array
  person['age'] = '20';
  // The key-value pairs in the Map are unique
  // In contrast to Set, Value overwrites the previous Value if the second Key is present
  person['name'] = 'hank';
  // Map values can be the same
  person['hobby'] = 'cooci';
  // Map value can be an empty string
  person['hobby'] = ' ';
  // The map value can be null
  person['height'] = null;
  print(person);    // {age: 20, name: hank, hobby: , height: null}
}
Copy the code

⑥ References

Flutter official documentation: https://flutterchina.club

The Dart official documentation: https://dart.dev/guides/language/language-tour

Geek college team: https://wiki.jikexueyuan.com/project/dart-language-tour/important-concepts.html

The Dart grammar learning: https://www.jianshu.com/p/9e5f4c81cc7d

The Dart syntax: https://www.pipipi.net/dart/dart-syntax.html

Here to recommend a very good iOS dry goods output point. Build iOS prosperity ecology, start from your little love 💖