Hopefully, before you read this article, you've read:

The basic syntax for Dart: A tour of Flutter: An appreciation of Dart object orientation from source code


1. Other common symbols and keywords

1.1: Cascade operators:.

Let’s look at the Paint object Settings:

----> ---- var paint = paint (); paint.strokeCap = StrokeCap.round; paint.style = PaintingStyle.stroke; Color = color (0xffBBC3C5); // Paint. IsAntiAlias = true; // Anti-aliasing paint. FilterQuality = filterQuality. // Anti-aliasing ---->[scenario 2: Cascading writing]---- paint.. strokeCap = StrokeCap.round .. Style = paintingstyle. stroke... Color = color (0xffBBC3C5) IsAntiAlias = true // Anti-aliasing.. filterQuality = FilterQuality.high;Copy the code

It’s very simple. It’s very elegant.


1.2: Conditional callers? .

---->[scenario 1: common call]---- void main() {var a = -5; print(a.abs()); //5} ---->[scenario 2: normal call is empty, will crash]---- var a = 5; a=null; print(a.abs()); ----> ---- var a = 5; //NoSuchMethodError: The method 'abs' was called on null. ----> a = null; print(a? .abs()); //nullCopy the code

1.3: Type judgment keywords,isis!andas

var b=10; print(b is String); //false print(b is num); //true print(b is! double); //true String c="12315"; print((c as Comparable<String>).compareTo("a")); Print ((c as num).abs()); // Type 'String' is not a subtype of type 'num' in type castCopy the code

2. Library use and visibility

2.1: Basic use of library
import 'dart:math'; / / import math library of built-in import 'package: flutter/material. The dart'; // Follow the file system path to the packageCopy the code

2.2: Naming conflicts in class librariesasUse of keywords

What happens when the sin function is in two packages and both packages are imported

---->[utils/color_utils.dart]---- sin(double d){ } ---->[main.dart:5]---- import 'package:toly/utils/color_utils.dart'; import 'dart:math'; void main() { sin(5); } ---->[solution]---- import 'package:toly/utils/color_utils. Dart 'as myMath; import 'dart:math'; void main() { myMath.sin(5); }Copy the code

2.3: Control the import of explicit and implicit parts

Hidden objects cannot be accessed by the outside world

import 'package:toly/utils/color_utils.dart' show sin; Import 'package:toly/utils/color_utils. Dart 'hide sin; // Hide only the sin functionCopy the code

2.4: Access control

Note that there are no private, public, and protected modifiers in Dart.

How to achieve access control, is a problem, the default is accessible.

---->[painter/person.dart]---- class Person{ String name; int age; Person(this.name,this.age); say(){ print("my name is $name and i am $age years old."); } } ---->[main.dart]---- import 'package:toly/painter/person.dart'; void main() { var toly = Person("toly", 25); print(toly.age); //25 toly.say(); //my name is toly and i am 25 years old. }Copy the code

As specified in Dart, an underscore before a name restricts external access, like _age.

Method names, file names, do not want to expose, just underline

---->[painter/person.dart]---- class Person{ String name; int _age; Person(this.name,this._age); say(){ print("my name is $name and i am $_age years old."); } } ---->[main.dart]---- void main() { var toly = Person("toly", 25); toly.say(); //my name is toly and i am 25 years old. print(toly._age); / / error}Copy the code

2.5:libraryandexportUse of keywords

Here made an example of animation, when using guide package: import ‘package: flutter/animation. The dart’;

Dart does only one inductive exposure action in the source code.

library animation;

export 'src/animation/animation.dart';
export 'src/animation/animation_controller.dart';
export 'src/animation/animations.dart';
export 'src/animation/curves.dart';
export 'src/animation/listener_helpers.dart';
export 'src/animation/tween.dart';
export 'src/animation/tween_sequence.dart';
Copy the code

3. The generic

Generics in Dart are very similar to Java in that they make types safer and code more elegant.

3.1: Use of generics

In the case of List, the class name List is appended when the class is defined. When used, List can be appended with a type. The advantage of this is that you will get an error when you try to add other types of data to the List object. This is how the type becomes safe.

---->[sky_engine/lib/core/list.dart:54]---- abstract class List<E> implements EfficientLengthIterable<E> { ---->[main.dart]---- void main() { var languages=List<String>(); Var odd=List<int>(); // define a list with a generic int}Copy the code


3.2:List,Map,Set special initialization

This is not a generic feature, just a quick way to initialize lists, maps, and sets.

It’s just a little bit weird, but I’ll tell you, we’ll see this a lot.

var languageList = <String>['Java', 'Dart', 'Kotlin'];
var markMap = <String,int>{'Java':100, 'Dart':80, 'Kotlin':60};
var languageSet = <String>{'Java', 'Dart','Kotlin'};
Copy the code

3.3: Generics qualification

Consistent with Java syntax, used to qualify the type region of a generic type

As specified in DiagnosticableNode below

class DiagnosticableNode<T extends Diagnosticable> extends DiagnosticsNode
Copy the code

3.4: Generic methods

In Dart, methods can also support generics, such as the following method:

When var e = foo

(“hello”); Foo

is an error.

T add<T>(T t) {
  return t;
}
Copy the code

4. Introduction to asynchronous operations

Asynchrony is a big topic that I’ll briefly mention and more on later.

4.1: Asynchrony is necessary in Dart

Dart is a single-threaded programming language, and time-consuming operations cause threads to block.

It’s like I’m boiling water, and I can’t do anything else until the water’s boiling, which is obviously not reasonable. I can sweep the floor while the water is boiling and then deal with it. I need a Future object for subsequent processing

class Water{ double temperature; Water(this.temperature); Future<Water> heat() {print(" open the heat switch "); return Future<Water> ((){ sleep(Duration(seconds: 3)); Temperature =100; return this; }); }} the main () {Water (0). The heat (). Then ((Water) {print (' Water is boiling, now temperature: ${Water. Temperature}, began to flush '); }); Print (" sweeping "); }Copy the code


4.2:asyncandawaitUse of keywords

Async means async, await means waiting. Note that the Future object is returned in the asynchronous operation

This object is used for subsequent processing, for example, to flush the water after boiling.

heat() async{
  var water = await Water(0).heat();
  print('水已经烧开,现在温度:${water.temperature},开始冲水');
  return water;
}
Copy the code

As can be seen, after opening the boiling water switch, it is followed by sweeping the floor, and then flushing the water after boiling, which is asynchronous operation.

More on this usage will be explained later when reading file resources.


5. Exception handling

5.1: The exception is not handled

As a result, the program crashes because of the FormatException

This was not what we wanted, and crashing would have resulted in a very poor user experience.

void main() { print(str2Num("a")); //FormatException: a } num str2Num(String str){ return num.parse(str); }Copy the code

5.2: Exception capture

This is similar to Java, where try… catch… The finally block of code

This way exceptions are logged and the program does not crash and exit. Statements in the finally code block are executed regardless of exceptions

num str2Num(String str){ var result= 0; try { result= num.parse(str); } catch (e) {print(' error: $e'); } finally {print(' block of code that will be executed at last '); } return result; }Copy the code

5.3: Specify exceptions or multiple exception capture

Using the ON keyword, you can specify a class of exceptions to catch.

num str2Num(String str){ var result= 0; try { result= num.parse(str); } on FormatException catch (e) {print(' Format exception: $e'); } on IOException catch(e){print(' IOException: $e'); } finally {print(' block of code that will be executed at last '); } return result; }Copy the code

6. The use of mixins

6.1: Subclass and superclass constructor call order

As you can see from the following code, the parent class constructor is called first

class Living { Living(){ print("Runner"); } } class Person extends Living{ Person(){ print("Person"); } } main(){ Person toly = Person(); } ----> ---- Runner PersonCopy the code

6.2: What is a mixin?

First mixin is a keyword that defines a class. The literal translation is to mix, to mix

Dart introduces the mixin keyword to support multiple inheritance. The mixin keyword is special in that classes defined by mixin cannot have constructors, which avoids conflicts in parent class constructors when multiple classes are inherited

class Living {
  Living(){
    print("Runner");
  }
}

class Runner {

  run(){
    print("run");
  }
}

class Walker{
  walk(){
    print("run");
  }
}

class Person extends Living with Walker,Runner{
  Person(){
    print("Person");
  }
}

main(){
  Person toly = Person();
  toly.run();
  toly.walk();
}
Copy the code

It is simple to use the class name after the with keyword, which is the mixin class

Mixins are the equivalent of mixing the capabilities of other classes into the current class, which is pretty cool. The only limitation is that mixin classes cannot have constructors. What if they did? An error.


6.3: About the mixin keyword

Classes defined using the class keyword can be used as mixin classes, such as the one above.

Mixin classes can also be defined using the mixin keyword, for example:

mixin Walker{ walk(){ print("run"); }}Copy the code

The only difference is whether you’re sure it’s a mixin class.

When you define a constructor in a mixin-declared class, an error is reported.


6.4: About mixing method duplication

Mixed with it

class Runner { go(){ print("Runner-go"); } } mixin Walker{ go(){ print("Walker-go"); } } class Person with Runner,Walker{ Person(){ print("Person"); } } main(){ Person toly = Person(); toly.go(); //Walker-go }Copy the code

This is the end of this article. If you want to taste Flutter quickly, Flutter For Seven days is a must-have. If you want to explore it, follow in my footsteps and complete a Flutter tour. In addition, I have a Flutter wechat communication group. You are welcome to join and discuss Flutter issues together. My wechat account is ZDL1994328.