- Dart data type 01 developed by Flutter
- These articles are all learning
Dart
The study notes recorded in the process are some basic knowledge, almost no technical content, mainly for the convenience of later use when easy to refer to - My article on Flutter and Dart syntax series can be read if you are interested
Dart data type
The Dart supports the following built-in data types
numbers
(digital)strings
(String)booleans
(Boolean)lists
(Also known asarrays
)maps
runes
Used to represent in a stringUnicode
Characters)symbols
The above data types can be initialized directly with literals
var str = 'this is a string' ;
var isStr = true;
Copy the code
You can also initialize using constructors. Because each variable in Dart refers to an object — an instance of a class — some built-in types have their own constructors
// You can use the Map() constructor to create a Map, like this
var map = new Map(a);Copy the code
Dart Numbers supports two types of Numbers:
int
: Integer value, whose value is usually located- 2 ^ 53
and2 ^ 53
Between, about9 * 10 ^ 16
, that is, support for 16 digitsdouble
:64-bit
(double precision) floating point number, consistentIEEE 754
standard
int
- Its value is usually located at
- 2 ^ 53
and2 ^ 53
between - That’s between minus 9,007,199,254,740,992 and 9,007,199,254,740,992
- In practice, more than 19 bits will cause an error
- Refer to question 1533 for more information
/ / the following definitions may be an error, the star int variables defined in 9223372036854775807 or less than - 9223372036854775808
var bil = 12345678901234567890;
Copy the code
Some common judgment attributes
const m1 = 12;
// Whether the value is negative or greater than 0 is false
print(m1.isNegative);
print(0.isNegative);
// Is it finite
print(b32.isFinite);
print(m1.isFinite);
// is infinite or infinitesimal
print(m1.isInfinite);
// Whether it is even
print(m1.isEven);
// Whether it is odd
print(m1.isOdd);
// Is it a NaN value
print(m1.isNaN);
// Symbol of data, -1.0: value less than 0, +1.0: value greater than 0, -0.0/0.0/NaN: value itself
print(21.sign); / / 1
print(- 23.sign); // -1
print(0.sign); / / 0
print(- 0.sign); / / 0
Copy the code
Int A commonly used function of a number type
const m3 = 24;
// Get the absolute value
print(m3.abs());
// To a string
print(m3.toString());
// power modulo; M3 to the fourth, modulo 3
print(m3.modPow(4.3)); / / 1
// return the greatest common divisor of m3 and 16
print(m3.gcd(16));
Return the remainder of m3 divided by 5
print(m3.remainder(5));
/ / to double
print(m3.toDouble());
// Compare sizes: 0: same, 1: greater, -1: smaller
print(m3.compareTo(30));
Copy the code
double
Here are some ways to define a double:
var y = 1.1;
var exponents = 1.42 e5;
Copy the code
Properties associated with type double
// Is it a NaN value
print(d0.isNaN);
// is infinite or infinitesimal
print(d0.isInfinite);
// Is it finite
print(d0.isFinite);
// Whether the value is negative or greater than 0 is false
print(d0.isNegative);
// Hash code generated from the code unit
print(d0.hashCode);
// Symbol of data, -1.0: value less than 0, +1.0: value greater than 0, -0.0/0.0/NaN: value itself
print(d0.sign);
print(1.23.sign);
print(0.0.sign);
// Returns the type of the runtime
print(d0.runtimeType); // double
Copy the code
The use of methods related to type double
// To a string
print(d0.toString());
// Take the integer and discard the decimal point
print(d0.toInt());
// Compare sizes: 0: same, 1: greater, -1: smaller
print(d0.compareTo(30));
// Get the absolute value
print(d0.abs());
// Round off
print(d0.round()); / / 13
// round up
print(d0.ceil()); / / 14
// round down
print(d0.floor()); / / 13
Round ().todouble ()
print(d0.roundToDouble()); / / 13.0
print(d0.ceilToDouble()); / / 14.0
print(d0.floorToDouble()); / / 13.0
// Retain the specified decimal number (rounded), not complement 0, string return
print(d0.toStringAsFixed(2)); / / 13.10
// Retain the number of digits of the variable (the total number of digits before and after the decimal point), not enough to complement 0, extra rounding
print(d0.toStringAsPrecision(10)); / / 13.09870000
/** toStringAsExponential * 1.toStringAsExponential(); // 1e+0 * 1.toStringAsExponential(3); / / 1.000 e+0 * 123456. ToStringAsExponential (); / / 1.23456 e+5 * 123456. ToStringAsExponential (3); / / 1.235 e+5 * 123. ToStringAsExponential (0); // 1e+2 */
/** toStringAsPrecision * 1.toStringAsPrecision(2); / / 1.0 * 1 e15. ToStringAsPrecision (3); / / 1.00 e+15 * 1234567. ToStringAsPrecision (3); / / 1.23 e+6 * 1234567. ToStringAsPrecision (9); / / 1234567.00 * 12345678901234567890. ToStringAsPrecision (20); // 12345678901234567168 * 12345678901234567890.toStringAsPrecision(14); / / e+19 1.2345678901235 * 0.00000012345. ToStringAsPrecision (15); / / 1.23450000000000 * 0.0000012345 e-7 toStringAsPrecision (15); / / 0.00000123450000000000 * /
Copy the code
Booleans
- To represent Boolean values,
Dart
There is a name forbool
The type of. - Only two objects are of type Boolean:
true
andfalse
Object, both of which are also compile-time constants - when
Dart
When you need a Boolean, it’s onlytrue
Objects are considered to betrue
And all the other values areflase
; As 1."aString"
, as well assomeObject
Equivalents are considered to befalse
const m = 1;
if (m) {
print('Is a Boolean');
} else {
print('Not a Boolean');
}
Copy the code
- in
Dart
Is the code that determines that the above statement is valid - But in the
Dart
Check mode run, the above code will throw an exception, indicatingm
The variable is not a Boolean value - Therefore, it is not recommended to use the above method to judge
Strings
Dart strings are UTF-16-encoded sequences of characters that can be created using either single or double quotation marks:
var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
// When there are single quotes inside single quotes (double quotes inside double quotes), you must use backslash \ bar escape
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";
Copy the code
Concatenation of strings
You can concatenate strings by simply writing adjacent strings together
var string = 'name''+''age'
Copy the code
Concatenate adjacent strings with +
var string1 = 'name' + '+' + 'age';
Copy the code
Reference variables
- in
Dart
The use of$
Symbols refer to variables or expressions - Expression reference:
${expression}
If the expression is a variable{}
Can be omitted
const num1 = 12;
// Reference the expression
const ageStr0 = 'age = $num1';
const ageStr1 = 'age = ${num1} is my age';
// Reference the expression
const ageStr2 = 'age = ${num1 * num1}';
Copy the code
Multiline string
Triple quotation marks using single or double quotation marks
const line1 = Tens of thousands of roads, safety first, driving is not standard, the family two lines of tears.;
const line2 = """ Thousands of roads, safety first, driving is not standard, family tears """;
Copy the code
Escape symbol
Declare the raw string (prefixed with r) by prefixing the string with the character r, or preceded by \ to avoid escaping \. This is especially useful in regular expressions
// Escape characters
print(R 'escape character, \n');
print('Escape character, \\n');
print('Escape character, \n');
Copy the code
Attribute is introduced
const string0 = 'https://www.titanjun.top/';
// Get each character of the string according to the index
print(string0[1]);
// Whether the string is empty
print(string0.isEmpty);
print(' '.isEmpty); // true
// Whether the string is not empty
print(string0.isNotEmpty);
print(' '.isNotEmpty); // false
// Returns the iterable of the string Unicode code
print(string0.runes);
// Returns a list of UTF-16 code units for strings
print(string0.codeUnits);
// Returns the hash code generated from the code unit
print(string0.hashCode);
// The length of the string
print(string0.length);
// Returns the runtime type of the object
print(string0.runtimeType); // String
Copy the code
Methods to introduce
const string0 = 'https://www.titanjun.top/';
// String comparison
print('titan'.compareTo('jun'));
// Case conversion
print(string0.toUpperCase());
print(string0.toLowerCase());
// Truncate string (leading index and ending index)
print(string0.substring(0.5)); // https
// The index is truncated to the end by default
print(string0.substring(12)); // titanjun.top/
// Split the string
print(string0.split('. ')); // [https://www, titanjun, top/]
print(string0.split(new RegExp(r"t"))); // [h, , ps://www., i, anjun., op/]
// Remove TAB Spaces and newlines from the string
const string1 = '\t\ttitanjun top\n';
print(string1.trim());
// Remove TAB Spaces and newlines at the beginning of the string
print(string1.trimLeft());
// Remove TAB Spaces and newlines at the end of the string
print(string1.trimRight());
Copy the code
endsWith
Determines whether a string ends with a character (string). The argument does not accept a regular expression
const str1 = 'titanjun.top';
print(str1.endsWith('p')); //true
print(str1.endsWith('/')); //false
print(str1.endsWith('top')); //true
Copy the code
startsWith
bool startsWith(Pattern pattern, [int index = 0]);
Copy the code
Determines whether a string begins with a character (string) and accepts a regular expression
const str1 = 'titanjun.top';
print(str1.startsWith('h')); //false
print(str1.startsWith('tit')); //true
print(str1.startsWith('it'.1)); //true
print(str1.startsWith(new RegExp(r'[A-Z][a-z]'), 1)); //false
Copy the code
indexOf
int indexOf(Pattern pattern, [int start]);
Copy the code
- Gets the index of the specified character (string) based on its first occurrence in the original string, from left to right
- You can start at the specified index, starting at 0 by default
- If there is no character (string) in the original string, the return value is: -1
const str2 = 'https://www.titanjun.top/';
print(str2.indexOf('titan')); / / 12
print(str2.indexOf('t'.5)); / / 12
print(str2.indexOf(new RegExp(r'[a-z]'))); / / 0
// If no characters are changed, -1 is printed
print(str2.indexOf('ppp')); // -1
Copy the code
lastIndexOf
int lastIndexOf(Pattern pattern, [int start]);
Copy the code
The effect is the same as indexOf, except that the order of indexOf is left to right and that of lastIndexOf is right to left
const str2 = 'https://www.titanjun.top/';
print(str2.lastIndexOf('t'.20)); / / 14
print(str2.indexOf(new RegExp(r'[a-z]'))); / / 0
// If no characters are changed, -1 is printed
print(str2.indexOf('ppp')); // -1
Copy the code
Fill a placeholder
String padLeft(int width, [String padding = ' ']);
String padRight(int width, [String padding = ' ']);
Copy the code
- Fill in placeholders before and after strings
- Parameter one: The number of bits of the string you want to get
- Parameter two: Supplementary character if the number of bits is insufficient
const str3 = '12';
print(str3.padLeft(2.'0')); / / 12
print(str3.padRight(3.'0')); / / 120
Copy the code
contains
bool contains(Pattern other, [int startIndex = 0]);
Copy the code
- Checks whether the string contains a character
- Checks if the character at the specified index is a character
bool contains(Pattern other, [int startIndex = 0]);
const str = 'Dart strings';
print(str.contains('D'));
print(str.contains(new RegExp(r'[A-Z]')));
print(str.contains('D'.0));
print(str.contains(new RegExp(r'[A-Z]'), 0));
Copy the code
Substitution characters
// Can only be replaced once. Parameter 3 is the starting index value. Default is 0
String replaceFirst(Pattern from, String to, [int startIndex = 0]);
// Replace all qualified characters (strings)
String replaceAll(Pattern from, String replace);
// Replace a range of characters
String replaceRange(int start, int end, String replacement);
// The following is an example:
// Replace the string
const str4 = 'titanjun12--0123';
print(str4.replaceFirst('t'.'T')); // Titanjun12--0123
print(str4.replaceFirst('12'.'21'.10)); //titanjun12--0213
// Replace all
print(str4.replaceAll('12'.'21')); //titanjun21--0213
print(str4.replaceAll('t'.'T')); //TiTanjun12--0123
// Interval substitution
print(str4.replaceRange(0.5.'top')); //topjun12--0123
Copy the code
List
A List object in Dart is an array in other languages
Create an array
// Create a List of specified length without adding/removing elements
List([int length]);
// Create a fixed-length List by specifying the length, and use fill to initialize the value at each position without adding/removing elements
List.filled(int length, E fill, {bool growable: false});
// Create a List of all elements,
// When growable is true (the default), the constructor returns a growable List. Otherwise, it returns a List of fixed length
List.from(可迭代 elements, {bool growable: true})
// Generate a List of all values
// Create a List of fixed length unless growable is true(the default)
List.generate(int length, E generator(int index), {bool growable: true})
// Create one that contains all elements without changing its length or elements
List.unmodifiable(可迭代 elements)
Copy the code
List
- If the parameters are set
length
(length
It cannot be negative ornull
), then createdList
It’s a fixed length - Elements can be modified, the number of elements cannot be modified, and elements cannot be deleted or added
var l1 = new List(3); //[null, null, null]
print(l1.length); / / 3
// The following is an error
l1.length = 1;
Copy the code
If length is not set, the length of the List is 0 and is growable
// Both ways are the same
var l10 = new List(a);var l11 = [];
// All work
l10.length = 3;
l10.add(1);
Copy the code
When creating a growable List with a specified length, the length is allocated only after creation
List growableList = new List().. length =500;
Copy the code
filled
- Creates a fixed-length object by specifying the length
List
And initializes the value for each position - All the elements are the same
fill
Value. If the specified value is a mutable object, thenList
All elements are the same object and are modifiable
var l2 = new List.filled(3.'l'); //[l, l, l]
var l3 = new List.filled(2[]);/ / [[], []]
l3[0].add(12);
print(l3); / / [[12], [12]]
Copy the code
from
- Create one that contains all
elements
theList
elements
theIterator
Specifies the order of elements.- when
growable
fortrue
(default), the constructor returns a growableList
. Otherwise, it returns a fixed lengthList
var l5 = new List.from([1.2.3.4]);
l5.add(5);
print(l5); // [1, 2, 3, 4, 5]
// The following add method returns an error
var l5 = new List.from([1.2.3.4], growable: false);
l5.add(5);
Copy the code
generate
- Generates a value that contains all values
List
Creates an element based on the index value growable
forfalse
Is created whenList
It’s a fixed length
var l4 = new List.generate(3, (int i) => i * i);
l4.add(14);
print(l4);
// [0, 1, 4, 14]
Copy the code
unmodifiable
- Create one that contains all
elements
UnmodifiableList
- unmodifiable
List
You can’t change its length or elements - If the element itself is immutable, then
List
It’s also immutable
var l6 = new List.unmodifiable([1.2.3.4]);
Copy the code
The List properties
var arr1 = [1.2.3.4];
// The first and last elements of the array
print(arr1.first); / / 1
print(arr1.last); / / 4
// Check whether the array is empty
print(arr1.isNotEmpty); // true
print(arr1.isEmpty); // false
// Array length, number of elements
print(arr1.length); / / 4
// Return the List in reverse order
print(arr1.reversed); // [4, 3, 2, 1]
// Returns an Iterator that is allowed to iterate over all elements of the Iterable
print(arr1.iterator);
// The runtime type of the object
print(arr1.runtimeType); // List<int>
// Get the hash value of the object
print(arr1.hashCode);
// Get the element by index
print(arr1[2]);
// Modify the element according to the index
arr1[1] = 11;
print(arr1);
Copy the code
The List method
increase
// Add elements
arr1.add(5);
// Add an array
arr1.addAll([10.12]);
Copy the code
To find the
var arr2 = ['one'.'two'.'three'.'one'.'four'];
// Whether to contain an element
print(arr2.contains('one')); // true
// Check whether the array has elements that meet the criteria
print(arr2.any((item) => item.length > 4)); // true
// Check whether all elements of the array meet the criteria
print(arr2.every((item) => item.length > 4)); // false
// Convert to Map with index as Key and corresponding element as Value
print(arr2.asMap()); // {0: one, 1: two, 2: three, 3: one, 4: four}
// Randomly shuffle the elements in the List
arr2.shuffle();
// Get the element by index, equivalent to arr2[3]
print(arr2.elementAt(3));
// Get the index of the element, starting at index 0 by default
print(arr2.indexOf('one')); / / 0
// Start with the second index
print(arr2.indexOf('one'.2)); / / 3
// If it cannot be found, return -1
print(arr2.indexOf('five')); // -1
// Get the index of the element from the back
print(arr2.lastIndexOf('one'));
print(arr2.lastIndexOf('one'.3));
print(arr2.lastIndexOf('five'));
// Returns the first element that satisfies the condition
print(arr3.firstWhere((item) => item == 'one'));
// Find the element that matches the condition, if there is only one element that matches the condition, return that element
// If no element is matched, or if more than one element is matched, an exception is thrown
print(arr2.singleWhere((item) => item.length == 5)); //three
// Return all elements except the original count
arr2 = ['one'.'two'.'three'.'four'];
print(arr2.skip(2)); // (three, four)
// Return all elements that do not meet this condition
print(arr2.skipWhile((item) => item.length == 3)); //(three, four)
// Return a new List of objects from start (inclusive) to end (exclusive), unchanged
print(arr2.sublist(1.3));
// Do not specify end, default to array end
print(arr2.sublist(2));
// Get the elements of an interval, return an array
print(arr2.getRange(1.3)); // ['two', 'three']
// Concatenate arrays into strings
print(arr2.join()); //onetwothreefour
print(arr2.join(The '-')); //one-two-three-four
// Return the original count of elements
print(arr2.take(2));
// Returns the array elements that match the condition until the condition value is false to stop filtering
arr2 = ['one'.'two'.'three'.'four'.'ten'];
print(arr2.takeWhile((item) => item.length == 3)); //(one, two)
Copy the code
delete
var arr2 = ['one'.'two'.'three'.'one'.'four'];
// Delete the specified element
// Return true if the element exists
print(arr2.remove('two')); // true
print(arr2); // [one, three, one, four]
// If there is no such element, return false
print(arr2.remove('five')); // false
// Delete by index, return the value of the deleted element
print(arr2.removeAt(1)); // three
print(arr2); // [one, one, four]
// Remove the last element and return the value of that element
print(arr2.removeLast()); // four
print(arr2); // [one, one]
[start, end] [start, end]
arr2.addAll(['six'.'seven'.'eight']);
arr2.removeRange(1.3);
print(arr2); // [one, seven, eight]
// Remove all elements that match the criteria
arr2.removeWhere((item) => item.length == 3);
print(arr2); // [seven, eight]
// Remove all elements in the List that do not meet the criteria
arr2.retainWhere((item) => item.length > 3);
print(arr2);
// Delete all elements
arr1.clear();
print(arr1); / / []
Copy the code
insert
var arr3 = [1.3.4];
// Insert an element somewhere
arr3.insert(1.10);
print(arr3); / / [1, 10, 3, 4]
// Insert an array
arr3.insertAll(2[12.32]);
print(arr3);
Copy the code
Important method
/ / filter Iterable < E >where(bool test(E element)) => new WhereIterable<E>(this, test); Iterable<T> map<T>(T f(E E)) => new MappedIterable<E, T>(this, f); Void sort([int compare(E a, E b)]); // iterative calculation, initialValue: initialValue, combine: T fold<T>(T initialValue, T combine(T previousValue, E element)) // Combine (T previousValue, E element) Compute function E reduce(E combine(E value, E element)) // Perform function operation void in iterative order for each element of the setforEach(void f(E element)) // Expand Each element of Iterable to 0 or more elements.Copy the code
Let’s take a look at how each of these functions is used
var arr2 = ['one'.'two'.'three'.'four'];
// The filter operation returns all elements that meet the criteria
print(arr2.where((item) => item.length == 3)); //(one, two, ten)
// Map a new array. The argument is a function
var array = arr2.map((item) {
return item + The '-';
});
print(array.toList()); // [one-, ten-, two-, four-, three-]
// Sort by default from small to large
arr2.sort();
print(arr2); //[four, one, ten, three, two]
// Set the criteria for sorting
arr2.sort((item1, item2) {
// If the result of the two comparisons is 0, the results may be different after sorting
return item1.length.compareTo(item2.length);
});
print(arr2); //[one, ten, two, four, three]
// iterative calculation, initialValue: initialValue, combine: calculation function
var arr4 = [1.2.3.4];
// Set the initial value
var result1 = arr4.fold(10, (prev, value) => prev + value); / / 20
var result2 = arr4.fold(2, (prev, value) => prev * value); / / 48
// The initial value is the value of the first element. The iterable must have at least one element. If it has only one element, the element returns directly
var result3 = arr4.reduce((value, element) => value * element); / / 24
// Operate on each element
arr2.forEach((item) {
print(item);
});
// expand, return a new Iterable in the order of the elements generated by calling f on each element
var pairs = [[1.2], [3.4]].var flattened = pairs.expand((pair) => pair).toList();
print(flattened); // => [1, 2, 3, 4];
var input = [1.2.3];
var duplicated = input.expand((i) => [i, i]).toList();
print(duplicated); // => [1, 1, 2, 2, 3, 3]
Copy the code
Because the space is too long, the remaining data types will continue to be studied and recorded in the next article
reference
- Dart official website syntax introduction – Chinese version
- Dart official website syntax introduction – English version
- Dart Language Chinese community
Please scan the following wechat official account and subscribe to my blog!