This article has authorized the public account “code egg”, please indicate the source of reprint

Before Flutter, you need to know the syntax of the language. Dart is, to be honest, very simple for those who know object-oriented languages like Java. Here I’ve summarized some of the syntax differences between Dart and Java, of course, only partially, but at my current level of learning, this is definitely enough to write the Flutter project. You can also check it for yourself. I provide you with a quick start on Dart

Tips: This article has no picture, no picture, no picture, may cause some discomfort, please pay attention, please pay attention, please fasten your seat belt, we are going to “drive”……

1. Variables

Dart variable types can be derived from specific assignments, such as: Var name = ‘kuky’ defines a String object name. You can also specify the specific type String name = ‘kuky’. If no variable is initialized, the default value is null. The default value for numeric variables is both null (unlike Java, where int defaults to 0.). If you need to define a constant, you can do so through final and const. Final variables can only be assigned once, and const is a compile-time constant.

2. Build-in-types

The built-in types of Dart include:

  • Numbers include int[-2^53 ~ 2^53], double[64-bit float number]

  • Strings Dart Strings are UTF-16-encoded sequences of characters that can be created using either single or double quotation marks.

    1. through= =Determines whether two strings are the same
    2. Through three pairs of single quotes'''aaa'''Or double quotation marks"""aaa"""You can create multi-line string objects
    3. Use prefixesrcreateraw string, the string will not escape, for example:var a = r'haha \n breakLine'printaObject is output as input, without line breaks
  • In the Booleans Dart, only true objects are considered true; all other values are false

  • Lists, for example: var list = [1, 2, 3, 4]

    Var list = const [1, 2, 3, 4]

    Var name =

    [‘Jone’, ‘Jack’]

  • Maps key-value pairs, e.g. Var map = {‘one’: 1, ‘two’: 2}

    Map [‘three’] = 3. If the search key does not exist, null is returned

    Var map =

    {‘one’: 1, ‘two’: 2}
    ,>

  • Runes are utF-32 code points for strings. Unicode code points are usually represented by \uXXXX, which is four hexadecimal numbers. For example, \u2665 returns the heart symbol ().

  • Symbols represents operators or identifiers declared in the Dart program and is rarely used

3. Function

Optional arguments to function methods are specified by {} in the argument list, for example:

void say(String name, {String word = 'hello'{})print('$name say $word');
  }

// assign the optional parameter by (optional parameter name + :)
main(){
    say('kuky', word: 'Hello World'); // kuky say Hello World
}
Copy the code

The word parameter is optional. The default value is Hello

4. Operators

The operator is almost similar to that of other languages, but the special assignment operator?? = and? The operator

var a = 1;
var b;
b ?? = a; // assign a to b if b is null, otherwise leave it unchanged
varc = size? .x;// Return null if size is null, otherwise return size
Copy the code
5. Conditional Expressions

Dart can replace if(){} else{} expressions with two special operators

/// condition? Expr1: Expr2 is the same as the Java ternary operator
var a = - 1;
a = a < 0 ? - 1 : a;
/// expr1 ?? expr2 
String toString() => msg ?? super.toString() If expr1 is not null, expr1 is returned; otherwise, expr2 is returned
Copy the code
6. Cascade Notaion(..)

Cascade operators (..) Multiple functions can be called consecutively on the same object and member variables can be accessed

class Size{
    double x;
    double y;

  @override
  String toString() {
    return 'Size{x: $x, y: $y}'; }}var size = Size();
// assign via the cascade operator, which can be more concise!! If the function returns void, it cannot cascade!!
print(size .. x =10
      ..y = 100
      ..toString()); Size{x: 10.0, y: 100.0}
Copy the code
7. foreach

Iterate through an object implementing the Iterable interface through the foreach loop

var items = [1.2.3.4.5];
var maps = {'a': 1.'b': 2};

items.where((i) => i > 2).forEach((i) => print(i));  / / 3, 4, 5
maps.forEach((key, value) => print('$key => $value')); // a => 1, b => 2
Copy the code
8. Switch and case

If you want the implementation to continue to the next case statement, you can use the continue statement to jump to the corresponding label and continue execution

var command = 'Close';
switch (command.toLowerCase()) {
  case 'close':
    print('close');
    continue open;
        
  open: // This is a tag
  case 'open':
    print('open');
    break;
}
Copy the code
9. Assert

If the result of the condition expression does not satisfy the requirement, you can use both assert statements to interrupt the code. For example, assert(a == 1);

10. Exceptions

All Dart exceptions are non-check exceptions. When catching exceptions, you can specify the exceptions type on and catch them

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  buyMoreLlamas();
} on Exception catch (e) {
  print('Unknown exception: $e');
} catch (e, s) { // The catch function can take one or two arguments, the first being the exception object thrown and the second being the stack information
  print('Something really unknown: $e');
  print('Stack trace:\n $s');
  rethrow; // The exception can be rethrown by rethrow
}
Copy the code
11. Classes

Dart classes are single-inherited, but mixin inheritance is supported. (Except for the Object class, each class has only one superclass.) All classes inherit from Object and determine the type of the instance by calling runtimeType. A getter method (implicitly) is automatically generated for each instance variable, and a setter method is automatically generated for non-final instance variables.

  • Constructors

    Dart’s constructor is similar to Java

    class Size {
      num x, y;
    
      Size(num nx, num y){
        x = nx;
        this.y = y; // This keyword is only used when names conflict, otherwise Dart recommends omitting this
      }
        
      Size(this.x, this.y); // Dart omits constructor assignment via syntactic sugar, as above
    }
    Copy the code

    If no constructor is defined, there is a default constructor. The default constructor has no arguments and calls the superclass’s no-argument constructor. A subclass does not inherit the constructor of the superclass, and a subclass has only one default constructor if it does not define a constructor.

    Dart creates multiple constructors for a class by naming constructors, while specifying the intent

    class Size {
      num x, y;
    
      Size(this.x, this.y);
    
      Size.fromJson(Map json){
        this.x = json['x'];
        this.y = json['y'];
      } Since constructors cannot be inherited, if you want a subclass to have the same named constructor as the superclass, you must implement the constructor in the subclass
      
      In addition to calling the superclass constructor, instance parameters can also be initialized before the constructor body is executed
      // Initializer lists are great for setting the values of final variables
      Size.fromJsonInit(Map json)
          : this.x = json['x'].this.y = json['y'];
    }
    Copy the code

    Constant constructors (if the class needs to provide an object with immutable state, do so via the const constructor)

    class ConstPoint {
      final num x;
      final num y;
    
      const ConstPoint(this.x, this.y);
    }
    Copy the code

    Factory method constructor (if a class does not need to provide a new object each time, the factory constructor does so)

    class HttpCore {
      HttpCore._internal();
    
      factory HttpCore() {
        if (_instance == null) _instance = HttpCore._internal();
        return _instance;
      }
    
      static HttpCore _instance;
    
      static HttpCore get instance => HttpCore();
      
      void _request(){
          / /...}}Copy the code
  • Each class implicitly defines an interface containing all instance members, and the class implements the interface, using abstract classes to implement Java interface-like functionality.

    abstract class Callback {
      void print(String msg);
    }
    
    class A implements Callback{
      @override
      void print(String msg) {
        print(msg); }}Copy the code
  • What is a Mixin Mixins Dart |

12. Asynchrony support
  1. Future

    loopIntegers() {
      // Use then to retrieve the Future object
      getListDelay().then((ints) => ints.forEach((i) => print(i)));
    }
    
    // Generate a Future object
    Future<List<int>> getListDelay() {
      return Future.delayed(Duration(seconds: 2), () = >List.generate(10, (delta) => delta));
    }
    Copy the code

    Simplify Future operations with async await

    runUsingFuture() {
      / /...
      findEntrypoint().then((entrypoint) {
        return runExecutable(entrypoint, args);
      }).then(flushThenExit);
    }
    
    // Simplify the then
    runUsingAsyncAwait() async {
      / /...
      var entrypoint = await findEntrypoint();
      var exitCode = await runExecutable(entrypoint, args);
      await flushThenExit(exitCode);
    }
    Copy the code

    This is sometimes managed by using future.wait () to call many asynchronous methods and wait for all methods to complete

    Future deleteDone = deleteLotsOfFiles();
    Future copyDone = copyLotsOfFiles();
    Future checksumDone = checksumLotsOfOtherFiles();
    
    Future.wait([deleteDone, copyDone, checksumDone])
        .then((List values) {
          print('Done with all the long steps');
        });
    Copy the code
  2. The Stream Dart | Stream is what

To install a Flutter environment, you must configure a mirror, configure a mirror, configure a mirror