Dart Basic Language Learning – Two types of variables

Weak type

var

If there is no initial value, it can be of any type

var a;
a = 'dart-var';
a = 123;
a = true;
a = {'key': 'val123'};
a = ['abc'];
Copy the code

Object

Dynamic arbitrary type, type checked during compilation

Object a = 'dart-Object';
a = 123;
a = [2222];
Copy the code

dynamic

Dynamic arbitrary type, compile phase does not check the type

  dynamic a = 'dart-dynamic';
  a = 123;
  a = [1111];
Copy the code

Compare var with Dynamic and Object

The only difference is that if var has an initial value, the type is locked

var a = 'var-dart';
dynamic a = 'dynamic-dart';
Object a = 'object-dart';
a = '123';
Copy the code

Strongly typed

Type declarations

After the declaration, the type is locked

  String a;
  a = 'string-dart';
  a = 123;
Copy the code

[image:3D54ECAC-156D-45C1-A179-2412CA92F5B3-34083-00021B12F58C29AA/2734B2E7-6484-464D-A5D5-4F99BD1F89EC.png]

Common type

| | name that | | — – | — – | | num digital | | | int | integer | | double | floating-point | | bool Boolean | | | String String | | | StringBuffer | String Buffer | | DateTime time date | | | Duration | time interval | | List List | | | Sets no repeat queue | | | Maps | kv container | | enum | | enums

 String a = 'String-Dart';
 int i = 123;
 double d = 0.12;
 bool b = true;
 DateTime dt = new DateTime.now();
 List l = [a, i, d, b, dt];
Copy the code

The default value

Everything is Object, and the default after variable declaration is NULL

var a;
String a;
print(a);
assert(a == null);
Copy the code

Assert checkpoint function that throws an error and terminates the program if the condition is not met

How to use

  • When writing API interfaces, use strong type. If the data does not meet the convention, the fault can be easily rectified when receiving data
  • When you’re writing a widget, you can use weak typing, so the code is fast and the type ADAPTS

PDF document sorting:

Dart Basic Language Learning – Part 1. PDF

Blog Source: Blog of rainy Night