Flutter learning note 04: Dart data type

One of the most basic characteristics of programming language is the data types it supports. These are the types of values that can be represented and manipulated in programming languages. The Dart language supports the following types:
1. Number int, double
2. String
3. bool
4. List (similar to array) list
5. Set
6. Map
7. Character (used to represent Unicode characters in a string)
8. Symbols

1. Number type

The number type in Dart is used to represent numeric text. There are two types of numbers in Dart:

1. Int: an integer value represents a non decimal value, that is, a number without a decimal point. The integer value is not greater than 64 bits, depending on the platform. On Dart VM, values range from - 263 to 263 - 1. When Dart is compiled into JavaScript, JavaScript numbers are used, with values ranging from - 253 to 253 - 1. For example, 10 is an integer. Use the int keyword to represent integer text.

2. * Double * *: Dart also supports decimal values, that is, values with decimal points. The double data type in Dart represents a 64 bit (double precision) floating-point number. For example, 10.10. The keyword double is used to represent floating-point text.

int and double are subclasses of num. Num types include basic operations +, -, / and *, and function methods such as abs(), ceil(), and floor(). If num and its subclasses cannot find the method you want, try using dart:math Library.
An integer is a number without a decimal point. Here are some examples of defining integer literals:

var x = 123;		
var hex = 0xDEADBEEF;

Double if the number contains a decimal. Here are some examples of defining double precision text:

var y = 1.199;		
var exponents = 1.42e5;

Starting from Dart 2.1, integer text is automatically converted to double precision when necessary:

double z = 10; //Equivalent to double z = 10.0

Therefore, to see whether a variable is an integer or a double precision number is not to see whether its value has a decimal point, but to see the keywords declaring it and what the system's default derivation is. For example, in the keywords declaring variables above, var x = 123 is deduced as an integer by default; var y = 1.199 is pushed to a decimal by default; and double Z= 10 is to tell the system directly that this variable is a double precision decimal, equivalent to double z = 10.0. Specific usage examples:

void dataSwitch(){
	//String to int
	var strToInt = int.parse("1");
	bool result = (strToInt == 1);
	print("String Convert to int Results of the latter comparison: $result");
	//String to double
	double strToDouble = double.parse("1.3");
	result = (strToDouble == 1.3000);
	print("String Convert to double Results of the latter comparison: $result");
	//int to String
	var ii = 2;		  int jj = 2;
	print("ii and jj Are these two numbers equal? ${ii==jj}");
	String intToString = 2.toString();
	String jjToString = jj.toString();
	print("intToString Are the two strings the same as "2"?${intToString == "2"}");
	print("jj Are the two strings the same as "2"?${jjToString == "2"}");
	double kk = 3.1415926;	  String doubleToString = kk.toString();
	print("doubleToString And "3.1415926"Is it the same? ${doubleToString=="3.1415926"}");
	////Keep the decimal of the specified number of digits after the decimal point, here is 3, which means keep the three significant digits after the decimal point and the last digit shall follow the rounding, which should be 3.145
	String stringAsFixed = kk.toStringAsFixed(3);
	print("stringAsFixed = ${stringAsFixed}");
	////The number of significant digits other than decimal point is reserved. Here is 5, which means that the number of significant digits other than decimal point is reserved. It should be 3.1415
	String stringAsPrecision = kk.toStringAsPrecision(5);
	print("stringAsPrecision = ${stringAsPrecision}");
}

The operation results are as follows:

The int type specifies the traditional bitwise shift (<, >), and (&), and OR(|) operators. For example:

bool rightMove = (3 << 1) == 6;
bool leftMove = (3 >> 1) == 1;
//Same as 1, otherwise 0
int andOperation = (3 & 2);
//1 is 1, otherwise 0
int orOperation = (3 | 2);
print("Shift right operation<<The result is ${rightMove}, \n Shift left operation>>The result is ${leftMove},"
    "\n And operation&The result is ${andOperation},\n Or operation | The result is ${orOperation}");

The operation results are as follows:

Literal numbers are compile time constants. Many arithmetic expressions are also compile time constants, as long as their operands are compile time constants compiled into numbers. Example:

const msPerSecond = 1000;
const secondsUntilRetry = 5;
const msUntilRetry = secondsUntilRetry * msPerSecond;
print("The result of constant operation is: ${msUntilRetry}");

The operation results are as follows:

Constant operation result: 5000

2. String:

A string represents a series of characters. For example, if you want to store some data, such as name, address, etc., you should use string data type. Dart strings are a series of UTF-16 code units. The character is used to represent a sequence of UTF-32 code units.
The keyword String is used to represent String text, and the String value is embedded in single or double quotation marks. So you can use single or double quotes to create a String:

void stringCharacteristic(){
  var s = 'string interpolation';
  print('Dart has $s, which is very handy.' ==
      'Dart has string interpolation, ' +
          'which is very handy.');
  print('That deserves all caps. ' +
      '${s.toUpperCase()} is very ' + 'handy!' ==
      'That deserves all caps. ' +
          'STRING INTERPOLATION is very handy!');
  print('That deserves all caps. ' +
      '${s.toLowerCase()} is very handy!' ==
      'That deserves all caps. ' +
          'string interpolation is very handy!');
}

The above three print logs are all true;
In development, we can also use three quotation marks with single quotation marks (') or double quotation marks (') to create multiline strings:

var s1 = '''
You can create
multi-line strings like this one.
''';
var s2 = """This is also a
    multi-line string.""";

You can create a "raw" string by prefixing it with r without escaping:

//Pay attention to the first r of the following string. Because of its existence, the following line break "\ n" will lose its meaning and function
var str01 = r'In a raw string, not even \n gets special treatment.';
var str02 = 'In a raw string, not even \n gets special treatment.';
print(str01);		
print(str02);

The operation results are as follows:

For const keyword decorated constants, pay attention to:

// In const string.
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';
const validConstString = '$aConstNum $aConstBool $aConstString';
print("All for const Constants make up a new constant: $validConstString");
// Not in const string.
var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1, 2, 3];
//General variables and const constants can't be combined into a new const constant. When compiling, an error will pop up, as shown in the following code:
const invalidConstString = '$aNum $aBool $aString $aConstList';
//Although it cannot be const constant, it can be declared as final, as follows:
final invalidConstStringFinal = '$aNum $aBool $aString $aConstList';
print("General variables and const Constants can only be combined into final Type constant, the result is: $invalidConstStringFinal");

The condition of false red burst is as follows:

The above code runs as follows:

3. Boolean type

Bool type in Dart. Only two objects have bool types: boolean literals: true and false, both of which are compile time constants.

Note: in the Dart language, the default value of variables of all types is null, that is to say, when declaring variable types, the default value is null, including the default value of variables of var key declaration. As follows:

void boolData(){
	  bool booleanVar;
	  print("bool The default value of a type variable is: $booleanVar");
	  String stringDefault;
	  var varDefault;
	  print("String The default value of a type variable is: $stringDefault,\nvar The default values of the variables declared by the keyword are: $varDefault");
	  int intDefault;
	  print("int The default value of a type variable is: $intDefault");
}

The operation results are as follows:

Other operation examples:

var varName;
var varDefaultName = "";
var varValue = "motion";
print("varName Is it a null value? ${varName == null},\nvarDefaultName Is it a null value? ${varDefaultName.isEmpty},\nvarValue Is it a null value? ${varValue.isEmpty}");
var zeroData = 0;
print("zeroData Is it equal to 0? ${zeroData == 0}");
var mod = 0/0;
print("Divisor 0: ${mod.isNaN}");

The operation results are as follows:

4. List type (similar to the list of array + partial list collection functions in Java)

The most common set in almost every programming language is an array or an ordered group of objects, characterized by ordered and repeatable elements. In Dart, an array is a List object, so most people call it a List:

var listData = [1, 2, 3, 4, 5]; //The array in Java is the same;

Like Java arrays, lists use indexes starting from 0, where 0 is the index of the first element, list.length-1 is the index of the last element. You can directly change the value of the corresponding index position by subscript. It can also be directly passed through list.length To get the length of the list:

print("The first element of the list is: ${listData[0]}, The third element is ${listData[2]}");
//Like Java arrays, you can directly change the value of the corresponding index position by subscript.
listData[2] = 100;
print("The length of the list is: ${listData.length}");
print("List after change listData The third element value of is: ${listData[2]}");

The operation results are as follows:

We can also add new elements at the end of the list through the add() method like the Java list collection, but the Dart language does not provide to add new elements at the specified location. That is to say, the length of list in Dart language can be changed even after declaration and assignment. In addition, we can remove the elements of the specified condition through the remove() series method:

////Add a new element at the end of the list through the add() method
listData.add(9);
listData.add(33);
////The way to add a new element at the specified location is the insert() series of methods
listData.insert(1, 23);
////The elements include: 1, 2, 100, 4, 5, 9, 33
print("After adding elements, the length of the new list is: ${listData.length}");
////Remove the element with element value 2. After removal, the list contains the following elements: 1, 100, 4, 5, 9, 33
listData.remove(2);
////Remove the element at index = 2. After removal, the list contains the following elements: 1, 4, 5, 9, 33
listData.removeAt(1);
////Remove the last element of the list. After removal, the list contains the following elements: 1, 4, 5, 9
listData.removeLast();
print("After a series of operations, the length of the new list is: ${listData.length}");
print("The first element of the list is: ${listData[0]}, The second element is: ${listData[1]}, The third element is: ${listData[2]},, The fourth element is: ${listData[3]}");

The operation results are as follows:

We can also create a list of const constant type, but the features of const constant type are: once declared and assigned, it can't be changed, including changing the value of an index position, deleting an element, adding an element, and once the above operations are carried out, an error throw exception will be reported:

//Let's create an array of const constants
const constList = [1,2,3,8,10];
constList[10] = 9;

The operation results are as follows:

Dart 2.3 introduces the extension operator ( )And null aware extension operators ( ?), which provides a concise way to insert multiple elements into a collection. For example, use the extension operator ( )Insert all elements of the list into another list:

const constList = [1,2,3,8,10];
var insertList = [14,...constList];
print("new insertList What is the length? ${insertList.length}");
print("insertList The first element is: ${insertList[0]}, The second element is: ${insertList[1]}, The third element is: ${insertList[2]}, The fourth element is: ${insertList[3]}, The fifth element is ${insertList[4]}, The sixth element is ${insertList[5]}");
//If the expression to the right of the extension operator may be null, you can avoid exceptions by using the extension operator (...?) that supports null:
var oldList;
////After this operation, insertList will empty the original data and then produce a new list: a list with only one element
insertList = [12, ...?oldList];
print("After splicing again insertList What is the length? ${insertList.length}");

Dart 2.3 also introduces collections of if and collection, which are used to build collections on condition (if) and repeat (for). Here is an example of using a collection to create a list of three or four items:

var promoActive = true;
var nav = ['Home',  'Furniture',  'Plants',  if (promoActive) 'Outlet'	];
print("nav What is the length of the list? ${nav.length}");

This is an example before using a collection to manipulate list items and then adding them to another list:

////This is an example before using a collection to manipulate list items and then add them to another list
var listOfInts = [1, 2, 3];
var listOfStrings = ['#0',  for (var i in listOfInts) '#$i'];
print("listOfStrings What is the length of the list? ${listOfStrings.length}");
print("The first element of the list is: ${listOfStrings[0]}, The second element is: ${listOfStrings[1]}, ""The third element is: ${listOfStrings[2]}, The fourth element is: ${listOfStrings[3]}");
print(listOfStrings[1] == '#1');

The above code runs as follows:

Common API collection:
——Length -- get the length of the array
——reversed -- reverses the array, but the return value is not an array, but an instantiated object of an abstract class, so it needs to be converted to an array through toList().
——isEmpty -- check whether the array is empty and return a Boolean value
——Add (e e e) - adds an element to the end of the array, which does not return a value. Parameters can only be one element, that is, only one element can be added at a time.
——Addall (iteratable I) - adds an element from an iteratable object to the end of the array without a return value.
——indexOf(element,start=0) - find an element and return the index of the array in the array. If there is no such element in the array, return - 1. This method receives two parameters, the first is the element to be found, and the second is a non required parameter, indicating the starting position of the search.
——remove(element) - delete the elements in the array, and return a Boolean value to indicate whether the deletion is successful.
——removeAt(index) - delete the element at the specified location, and the result returns the deleted element.
——fillRange(start,end,element) - fills the elements in [start, end]. This method does not return a value
——insert(index,element) - inserts an element at a specified location, and the method does not return a value.
——insertAll(index,iterable) - inserts multiple elements at a specified location, and the method does not return a value.
——toList() -- converts an iteratable type to an array.
——join(separator) - converts an array to a string with a separator as the parameter.
——forEach(function) - traverses an array. This method does not return a value: list.forEach ((item) => print(item));
It should be noted that there is only one parameter in the callback function, that is, the value of the element, without index!! Moreover, the parentheses cannot be omitted when the arrow function has only one parameter.

1. map(function) - processing method, which does not change the original array, but returns a new iteratable object, and the parameter is a callback function.
2. any(function) - traverses an array. Each element executes a callback function once to determine whether it meets the condition of callback function return value. If one or more elements meet the condition, it returns true. For example:

var list = <int>[1,2,3,4,5];	  
bool result = list.any((item) => item > 2);  
print(result);

There are three traversal output modes of list:

var list = <int>[1,2,3,4,5];
list.forEach((element) {	
	print("forEach Traverse output mode: ${element}");	
});
for(var i=0;i<list.length;i++){  
	print("Conventional for Loop traversal output mode: ${list[i]}");	
}
for(var item in list){  
	print("for--in Loop traversal output mode of: ${item}");	
}

5. Set

A set in dart is a set of unique items whose elements are out of order and not repeated. Dart supports collections provided by set text and set types. Next is a simple Dart Set, created with set text:

var halogens = {
	'yiibai.com', 'chlorine', 
	'bromine', 'iodine', 'astatine'
};

To create an empty Set, use {} with type parameters before it, or assign {} to a variable of type Set:

////To create an empty Set, use {} with type parameters before it, or assign {} to a variable of type Set:
var names = <String>{};		
Set<String> nameSet = {};
print("Two set Is the set equal? ${names == nameSet}");
////Pay special attention to the following points (this writing method will create a map, not a set set).
////var names = {};

Use the add() or addAll() methods to add items to an existing collection:

////Use the add() or addAll() methods to add items to an existing collection:
names.add('fluorine');		
nameSet.add("value");
names.addAll(halogens);		
names.addAll(nameSet);

use set.length To get the number of items in the collection:

////Use. length to get the number of items in the collection:
print("names Length of set: ${names.length}");

To create a collection of compile time constants, add const before the set text:

////To create a collection of compile time constants, add const before the set text:
final constantSet = const {  'iodine',  'astatine',	};
////The following operation will report an error: Unsupported operation: Cannot change unmodifiable set
constantSet.add('helium');

The operation results are as follows:

Common API of set:
——Length - set length
——First -- returns the first element of the collection
——Last -- returns the last element of the collection
——isEmpty -- judge whether the set is empty
——add(E) -- add elements to the end of the collection
——addAll(E) - adds all elements of an iteratable object to the end of the collection
——Remove -- delete an element
——clear() -- clear the set
——contains(E) - determines whether a set contains an element
——containsAll(E) - determine whether the set contains all elements in an iterative object
——toList() -- convert to array

6. Map

A Map is an object associated with a key and a value. The key key and value can be any type of object. Each key appears only once and cannot be repeated. Otherwise, the value corresponding to the next key will overwrite the value stored in the previous key, but the value is not limited at all. Dart supports mappings provided by mapping text and Map types. This rule is exactly the same as the Map rule in Java.
There are two ways to create a Map:

1. Create with mapped text:
//This method is applicable to a limited number of keys and is convenient to use when the exact key value is known
var textMap = {"service": "Java", "Android": "Kotlin", "Flutter": "Dart"};
var intMap = {1:"Java",2:"C",3:"Python",4:"C++",5:"C#"};

var intConstructionMap = Map();
intConstructionMap[1] = "Java";	
intConstructionMap[2] = "C";
intConstructionMap[3] = "Python";	
intConstructionMap[4] = "C++";
intConstructionMap[5] = "C#";
//When we need to add new elements, call the following methods to add new elements or replace the existing elements:
textMap["System"] = "C";			
intMap[6] = "VB";
strConstructionMap["System"] = "C";		
intConstructionMap["auxiliary"] = "VB";
//How to get elements:
var getTextMapValue = textMap["System"];		
var getIntMapValue = intMap[6];
var getStrConstructionMapValue = strConstructionMap["System"];
var getIntConstructionMapValue = intConstructionMap["System"];
print('getTextMapValue == ${getTextMapValue}, getIntMapValue == ${getIntMapValue}, getStrConstructionMapValue == ${getStrConstructionMapValue}, getIntConstructionMapValue == ${getIntConstructionMapValue}');
print("getIntConstructionMapValue It's a null character string? ${getIntConstructionMapValue=="null"},\ngetIntConstructionMapValue It's a null Object? ${getIntConstructionMapValue==null}");

The operation results are as follows:

I don't know if you find this running result very strange, that is, the value of the last getIntConstructionMapValue is printed out as null, that is, we didn't get the value, and from the later judgment results, we can also know that the System returned me a null object, rather than a "null string". But we explicitly added the value "System" with the key "System" to the intConstructionMap set. Why not get it?

In fact, it's not hard to look at the code carefully. When we added elements to the intConstructionMap set, the key values we used were all integers. But when we added the value "System" at the end, the key values we used were string type "System". Because of the different data types, it certainly led to the failure of the results we added.

If we change the key key used to add a value of "System" to the intConstructionMap set from "System" to any integer, we can succeed:

intConstructionMap[6] = "VB";
var getIntConstructionMapValue = intConstructionMap[6];

The operation results are as follows:

This also shows that when the mapping Map uses the key to find the value value, if it is not found, it will return us a null object. This should be noted in development.
Now let's look at the traversal output of the mapping Map. The mapping Map still uses the intConstructionMap above:

intConstructionMap.forEach((key, value) {
  print("intConstructionMap Mapped key===${key},value===${value}");
});

The operation results are as follows:

Common API for mapping Map:
——Length - length
——Keys -- returns an iterative set containing all keys
——Values -- returns an iterative set of all values
——isEmpty -- judge whether the set is empty
——addAll() -- add key value pairs in all iteration objects
——remove(key) - delete a key value pair

print("intConstructionMap Length of mapping length===${intConstructionMap.length}");
print("intConstructionMap Is it empty? ${intConstructionMap.isNotEmpty}");
print("intConstructionMap Contains the specified key Is it worth it? ${intConstructionMap.containsKey(7)}");
print("intConstructionMap Contains the specified value Is it worth it? ${intConstructionMap.containsValue("VB")}");

print("textMap Contains the specified key Is it worth it? ${textMap.containsKey("System")}");
textMap.remove("System");
print("textMap realization remove Remove assignment key The specified key Is it worth it? ${textMap.containsKey("System")}");
//The main function of the following code is to return iterator set Iterable containing key and value
Iterable iterableKey = intConstructionMap.keys;
iterableKey.forEach((element) {
  print("Loop through all values Key Iteratable set of iterableKey: key==${element}");
});
Iterable iterableValue = intConstructionMap.values;
iterableValue.forEach((element) {
  print("Loop through all values Value Iteratable set of iterableValue: value==${element}");
});

The operation results are as follows:

Tags: Java Programming Javascript Python

Posted on Sat, 06 Jun 2020 00:07:34 -0700 by msandersen