This article is first published in the wechat public account “Android development journey”, welcome to follow, get more technical dry goods

Wan-android Jetpack VersionAndroid Jetpack architecture for componentized application developmentWelcome to star

Project address of Flutter wan-AndroidFlutter Wan – AndroidWelcome to star

An overview of the

Dart has been a strongly typed, statically typed language since 2.0. This is similar to Java, C#, etc. That is, the type of the variable is known at compile time and that’s a statically typed language. Developers need to specify variable types at development time. What are the advantages of this? All type checking can be done by the compiler. Trivial errors can be predicted in advance. Dart is also an object-oriented programming language. Languages like Python, Java, Koltin, PHP, and so on are all object-oriented.

Dart features: JIT: Just-in-time compilation, faster compilation and faster code reloading during development. However, the disadvantage is that the code needs to be compiled into mechanical code at runtime, so it is intuitively slow. Therefore, we sometimes find lag during development, but the effect will become better after release package is issued. AOT: Pre-compiled, and compiled to binary during release, so loading is faster and smoother.

Common data types

The foundation of any language is data types, and DART is no different. Dart has numeric, string, Boolean, set, and VAR types.

Num type

Num is the parent of the number type in DART and has two subclasses: int and double. When num is specified, it can be a decimal or an integer, but once a specific type is specified, only that type can be assigned.

  void _numType() {num num1 = -2.0; Num2 = 4; // define num as you too int num3 = 5; // Double num4 = 6.0; // only double precision}Copy the code

These types can be converted to each other, for example:

    print(num1.abs()); // Take the absolute value of output 2.0print(num2.toDouble()); // Convert to 4.0 as a decimalprint(num3.toString()); // Convert to string output"5"
    print(num4.toInt()); // Convert to integer output 6Copy the code

Type String

String can be defined using either single or double quotation marks. Multiple variables can be separated by commas after defining a String. Concatenation strings in DART can be + sign links and can also be usedXx, if it is an expression, wrap it with ${XXX}.

  void _stringType() {
    String str1 = 'str1', str2 = "str2"; // Define the strings str1 and str2 String str3 ="String data type"; // Define String str3 String str4 ='str1=$str1; str2=$str2'; // Concatenate the String str5 = with the $character"str1=" + str1 + " str3="+ str3; // Concatenate string with + sign}Copy the code

There are also some common apis for strings, such as string interception, getting a specified string position, matching the beginning of a string, and so on.

    print(str3.substring(1, 5)); String data outputs string dataprint(str3.indexOf("Data")); // Get position output 3print(str3.startsWith("Word")); // Matches the start stringtrue
    print(str3.replaceAll("String"."The dart String")); // Replace the String data type for dartprint(str3.split("The number")); // Cut enough string output [string, data type]Copy the code

Boolean type

The Dart Boolean type is a strong bool. A value of bool is considered true only if it is true. Bool and some commonly used operators such as | | (or) or && (and), at the time of operation, teach you a mantra is, and the same true is true, or false is false.

  void _boolType() {
    bool success = true; // define bool astrue
    bool failure = false; // define bool asfalse

    print(success || failure); // or operation outputtrue
    print(success && failure); // And the operation outputfalse
  }
Copy the code

Collection types

Dart defines collections directly using List List =[]. If no generics are specified, the default type is Dynamic. Data of any data type can be added to the collection. In addition to adding elements at initialization, you can also use apis to add data to collections, add to add single data, and addAll to add collections. Another way to generate a collection is with list. generate, where the first parameter indicates the size of the collection and the second parameter indicates the elements of the collection.

  void _listType() {
    List list = [1, 2, 3, "list"]; // The generic type is dynamic //type 'List<dynamic>' is not a subtype of type 'List<int>'IntList <int> intList = list; intList <int> intList = list; List<int> intList2 = [1, 2, 3, 4, 5]; // define the int collection list.add("hello"); // Add a single element list.addall (intList2); // Add collectionprint(list); // output [1, 2, 3,"list"."hello",1, 2, 3, 4, 5]

    List<String> strList = List.generate(2, (index)=> "I was the first$indexElement"); // Generate defines a collection of stringsprint(strList); // output [I am element 0, I am element 1]}Copy the code

With a set, we need to iterate over it. Common ways to iterate over a set in DART are:

    for (int i = 0; i < list.length; i++) {
      print(list[i]);
    }

    for (var data in list) {
      print(data);
    }

    list.forEach((it) {
      print(it);
    });
Copy the code

The output results of the above three traversal modes are:

1, 2, 3, "list"."hello"One, two, three, four, fiveCopy the code

The Map type

A Map type is an object associated with a key and a value. The key and value can be any type of data, and the key is unique. If the key is duplicated, the newly added data overwrites the previously added data. To define a map type, look directly at the code:

  void _mapList() {
    Map map = {"lisi": 20."zhangsan": 24}; Map2 = {}; map2 = {}; map2[11] = 20; map2["zhangsan"] = "24"; // The above two effects are the same and do not specify a generic type. Map<int, int> intMap = {1: 2, 3: 4}; // Specify map generic}Copy the code

Let’s look at the Map traversal:

    map.forEach((key, value) {
      print(
          "key:$key,value:$value"); // output key:lisi,value:20 and key:zhangsan,value:24}); map.map((key, value) {returnMapEntry(value, key); }). ForEach ((key, value) {// return a new map object by reversing the key value.print("key:$key,value:$value"); // output key:20,value:lisi and key:24,value:zhangsan});for(var key inMap.keys){// Iterate over the key element of a map and iterate over the values of map.keysprint(key); // Output lisi and zhangsan}Copy the code

Dynamic, Var, Object

Dynamic: The dynamic data type, which is the base type for all Dart objects. In most cases, it is not usually used directly. Variables defined through it turn type checking off, meaning dynamic x = ‘hello world’; The x.foo() method does not return static type checks, but it will crash at runtime. Since x does not have a foo() method, it is recommended that you do not use dynamic directly when programming.

Var: is a keyword that means “I don’t care what type is here.” , the system will automatically infer the type runtimeType; And once a type is specified, it cannot be changed.

Object: is the base class of the Dart Object. You can call the toString() and hashCode() methods of obj because Object provides these methods, but static type checking will give you an error if you try to call obj.foo().

The main difference between Dynamic and Object is in static type checking.

object-oriented

Class definition and construction

Define a Dart class using the class keyword plus the class name. The constructor is the same as the class name. By default, all classes inherit from Object. Some methods and variables can be defined, such as:

class Person { String name; int age; Person(this.name, this.age); // Overriding the parent toString method is also an important embodiment of polymorphismtoString() {
    return "name=$name,age=$age"; }}Copy the code

A class extends from another class using the extends keyword. If the parent class does not have a default no-argument constructor, then the subclass needs to initialize the parent class using super. The variables of the subclass are initialized using this.xxx, as in:

class Worker extends Person { String workType; String workAddress; / / by this initial anti-fuzzy class fields, will the other fields to the parent class initializes the Worker (enclosing workType, enclosing workAddress, String name, int age) : super (name, age); }Copy the code

In the code above: super(name,age) is called as an initializer. In addition to calling the parent constructor, instance variables can also be initialized, separated by commas.

class Worker extends Person { String workType; String workAddress; String companyName; // Use this to initialize the subclass fields, leaving the other fields initialized by the parent class, where companyName is specified. Worker(this.workType, this.workAddress, String name, int age) : companyName = // Worker(this.workType, this.workAddress, String name, int age) : companyName ="world",
        super(name, age);
}
Copy the code

We can also initialize instance classes by naming constructors. Xx () is the class name. The main thing to note is that when a variable is final, the named constructor requires that it be initialized in the constructor.

class Worker extends Person { ...... Worker.begin(Worker work) : super(work.name, work.age) {print("Named constructor"); } //Worker.begin(worker.work, this.workaddress) : // worker.begin (worker.work, this.workaddress) : super(work.name, work.age) { //print("Named constructor");
  //}
  
}
Copy the code

Factory constructors simply return the same instance class, which can be interpreted as a singleton pattern in Java.

class Logger {
  static Logger _logger;

  factory Logger() {
    if (_logger == null) {
      _logger = Logger._initInstance();
    }
    return_logger; } // Initialize logger._initinstance () by naming the constructor; }Copy the code

Another constructor, a combination of named and factory constructs, is commonly used when mapping JSON to Object during network requests, and has the advantage of not passing the class’s final variables as arguments to the constructor. Provides a flexible way to get class objects. Definition format: Factory class name. The method name.

class Worker extends Person {
 
  ......
 
  factory Worker.workHard(Worker work) {
    return Worker.begin(work, ""); }}Copy the code

Dart implicitly defines setter methods by default and adds getter methods for non-empty variables. However, after adding private, the external world can not access the variable, we need to manually add set and GET methods.

class Worker extends Person {

  ......

  double _salary;

  setsalary(double value) => _salary = value; get salary => _salary; . }Copy the code

Abstract classes and methods

Use the abstract modifier to define an abstract class that cannot be instantiated. Abstract classes are very useful when defining interfaces, and in fact contain some implementations. If a class inherits from an abstract class it either implements its abstract methods or defines itself as an abstract class. An abstract class does not have to have abstract methods, but a class with abstract methods must be an abstract class.

Void eat(); void eat(); } // implement abstract class Dog extends Animal {// implement eat method @override voideat() {
    print("Bone gnawing"); }}Copy the code

mixins

Mixins are a way to reuse code across multiple class hierarchies. To use mixins, the with keyword is followed by the names of one or more mixins (separated by commas), and with is followed by the extends keyword.

Mixins are characterized by creating a subclass of Object without declaring any constructors and without calling super.

// Declare mixins class Pig {voidaction() {
    print("Eat and sleep"); }} // Mixins extends Animal with Pig {@override voidaction() {
    print("Catch a mouse.");
  }

  @override
  void eat() {
    print("Eat cat food"); }}Copy the code

Method definition

A method consists of a return value type + a method name + an argument. The return value type can be default, void, or a concrete type. Normally this is done by method name, but there is a special case for anonymous methods. Parameters are classified into parameter type and parameter name. The parameter type can be default. Parameters are divided into optional and default parameters, which are defined using {}.

String fromWhere(country, {String city, String town ="Little Red Hat Village"{})if(city ! = null) {return "I come from$country $city $town";
    } else {
      return "I come from$country $town"; }}}Copy the code

Let’s call print and see:

FunClass funClass = FunClass();
print(funClass.fromWhere("Grimm")); // I come from Ha-ha Village in Green Countryprint(funClass.fromWhere("Grimm", city: Once Upon a Time)); // I come from Ha-ha Village, fairy tale town, Grimm countryCopy the code

Anonymous methods, sometimes referred to as lambda or closure closures, can be assigned to a variable by calling the variable name.

var printI = (i) => print(i); 
Copy the code

Use:

FunClass funClass = FunClass();
funClass.printI(999);
Copy the code

The generic

Generics address the reuse of classes, interfaces, methods, and support for non-specific data types.

class Cache<T> {
  static final Map<String, Object> _cached = Map();

  void setItem(String key, T value) { _cached[key] = value; } /// the generic method T getItem(String key) {return_cached[key]; }}Copy the code

Here we define a cache class that stores generic types to improve code reuse.

Type constraints can sometimes be used when specific types are expected in a generic implementation of a generic-like interface.

class Member<T extends Person> { T _person; /// generics constrain type Member(this._person); StringfixedName() {
    return 'fixed:${_person.name}'; }}Copy the code

conclusion

This article mainly covers the basics of DART, which is commonly used in Flutter, but there are many other topics that are not covered. Here are a few dart learning sites to use.

www.dartlang.org

The dart. Dev/guides/lang…

Dart.goodev.org/guides/lang…

I have uploaded all the Demo source code to the background, follow the public account reply “Dart foundation” to get the download link.

If you think the article is good, please share it with your likes. Yours is definitely my biggest encouragement and support.

Recommended reading

A detailed guide to the Integration of the Flutter module into the Android project

A detailed guide to iOS project integration with the Flutter module

A detailed guide to The communication between Android and Flutter