• Dart data type 02 developed by Flutter
  • These articles are all learningDartThe 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
  • The Dart data type 01 of Flutter development has been introduced in a previous article. The rest of the commonly used data types are mainly recorded here
  • My article on Flutter and Dart syntax series can be read if you are interested

Map

  • key-valueKey-value pairs (can be used with associatedkeyretrievevalueValue), the legendary dictionary
  • MapIn thekeyThe number of each is limitedkeyThere’s a related onevalue
  • Map, as well as its keys and values, are iterable, in the order of iterationMapDifferent type definitions
    • A HashMap is unordered, which means that the order in which it iterates is uncertain
    • LinkedHashMapAccording to thekeyThe insertion order is iterated over
    • SplayTreeMapAccording to thekeyThe sort order is iterated over
  • whenMapWhen an operation is being performed, it is usually not allowed to changeMap(Add or removekey)

Create a Map

Map(a)// Create a Map instance. The default implementation is LinkedHashMap.

Map.from(Map other)
// Create a LinkedHashMap instance that contains all the key-value pairs of Other.

Map.fromIterable(可迭代 iterable, {K key(element), V value(element)})
// Create a Map instance where keys and values are computed from the elements of iterable.

Map.fromIterables(可迭代<K> keys, 可迭代<V> values)
// create a Map instance by associating the specified keys with values.

Map.identity()
// Create a strict Map using the default implementation LinkedHashMap.

Map.unmodifiable(Map other)
// Create an immutable hash based Map containing all items of Other
Copy the code

Specific use of each creation method

  // Create a Map instance and insert the order
  var dic = new Map(a);print(dic);  / / {}

  // Create a new Map based on a Map and insert it in order
  var dic1 = new Map.from({'name': 'titan'});
  print(dic1);  // {name: titan}

  // Create a Map based on the List
  List<int> list = [1.2.3];
  // By default, both key and value are elements of the array
  var dic2 = new Map.fromIterable(list);
  print(dic2);  // {1: 1, 2: 2, 3: 3}
  // Set the key and value values
  var dic3 = new Map.fromIterable(list, key: (item) => item.toString(), value: (item) => item * item);
  print(dic3);  // {1: 1, 2: 4, 3: 9}

  // Two arrays map to a dictionary, insertion order is sorted
  List<String> keys = ['name'.'age'];
  var values = ['jun'.20];
  // If there is the same key value, the following value overwrites the previous value
  var dic4 = new Map.fromIterables(keys, values);
  print(dic4);  // {name: jun, age: 20}

  // Create an empty Map that allows null keys
  var dic5 = new Map.identity();
  print(dic5);  / / {}

  // Create an immutable, hash-based Map
  var dic6 = new Map.unmodifiable({'name': 'titan'});
  print(dic6);
Copy the code

Relevant properties

The operations for related attributes and common attributes in Map are as follows:

  var map1 = {'name': 'titan'.'age': 20};
  / / hash value
  print(map1.hashCode); 

  // Runtime type
  print(map1.runtimeType);  //_InternalLinkedHashMap<String, Object>

  // Whether is null, null cannot be determined, will report an error
  print(map1.isEmpty);  // false

  // Whether it is not null
  print(map1.isNotEmpty);  // true

  // Number of key-value pairs
  print(map1.length);   / / 2

  // All key values, return the Iterable
      
        type
      
  print(map1.keys.toList());  // [name, age]

  // All values, return the Iterable
      
        type
      
  print(map1.values.toList());   // [titan, 20]

  // The value is based on key
  print(map1['name']????' ');   // titan

  // Assign a value based on key
  map1['age'] = 30;
  print(map1);   // {name: titan, age: 30}
Copy the code

Correlation function

  var map2 = {'name': 'titan'.'age': 20};

  // Add a map
  map2.addAll({'blog': 'titanjun'});
  print(map2);
  // {name: titan, age: 20, blog: titanjun}

  // Check whether the specified key is included
  print(map2.containsKey('age'));  //

  // Check whether the specified value is included
  print(map2.containsValue('titan'));

  // Manipulate each key-value pair
  map2.forEach((key, value) {
    print('key = $key, value = $value');
  });

  // Find the value corresponding to the key, or add a new value with key.length
  for (var key in ['name'.'age'.'king']) {
    // The function returns the corresponding value found
    print(map2.putIfAbsent(key, () => key.length));
  }
  print(map2);
  // {name: titan, age: 20, blog: titanjun, king: 4}

  // To a string
  print(map2.toString());

  // If a key pair is deleted, the value corresponding to the deleted key is returned. If no key pair is deleted, null is returned
  print(map2.remove('blog'));  //titanjun
  print(map2.remove('coder'));  //null
  print(map2);

  // Delete all key-value pairs
  map2.clear();
  print(map2);  / / {}
Copy the code

可迭代

  • A collection of values or elements accessed in sequence,ListThe set also inherits from可迭代
  • ListandSetIs also可迭代.dart:collectionThere are also many in the library
  • Part of the可迭代Collections can be modified
    • toListorSetAdding an element changes all the elements that the object contains.
    • Add new to MapKeyWill change everythingMap.keysThe element.
    • After the collection changes, the iterator created will supply all the new elements, and may or may not maintain the current order of elements

Create a way

  // Create an empty iterable
  var ite = 可迭代.empty();
  print(ite);   / / ()
  
  // Create an Iterable that dynamically generates elements from sequences
  var ite1 = 可迭代.generate(5);
  print(ite1);  // (0, 1, 2, 3, 4)
Copy the code

All Iterable properties and functions are described in detail in the List module of Dart datattype 01 for Flutter development. Since List is derived from Iterable, all Iterable properties and methods are in List

Runes

  • inDart,RunesRepresenting a stringUTF-32Character set, another kindStrings
  • UnicodeA unique numeric value is defined for each character, punctuation mark, emoji, etc
  • Due to theDartThe string isUTF-16So expressing sequences of 32 characters in a string requires a new syntax
  • Usually use\uXXXXIn terms of sigma, sigma hereXXXXIt’s four hexadecimal numbers, for example, a heart symbol(has)is\u2665
  • For non-four values, place the coded value in braces, e.g., smiley faceemoji(😆) is\u{1f600}
  • StringClasses have attributes that can be extractedruneinformation
    • codeUnitAtandcodeUnitProperty returns 16 characters
    • userunesProperty to get the stringrunesinformation
  var clapping = '\u{1f44f}';
  print(clapping);  / / 👏
  print(clapping.codeUnits);  / / [55357, 56399]
  print(clapping.runes.toList());  / / [128079]
Copy the code

Simple to use

  // Create from a string
  Runes runes = new Runes('\u2665, \u{1f605}, \u{1f60e}');
  print(runes);
  // (9829, 44, 32, 128517, 44, 32, 128526)
  // Outputs a string of special characters
  print(new String.fromCharCodes(runes));
  / / has 😅, 😎
Copy the code

Since Runes also inherits from Iterable, properties and methods in Runes are used in the same way as Iterable. For details, refer to the Dart datatype 01 of Runes and Flutter development

Symbols

  • aSymbolObject representsDartAn operator or identifier declared in a program
  • You probably won’t need itSymbol, but this feature can be valuable in cases where identifiers are referenced by name, especially in obfuscated code where the names of identifiers are obfuscated, butSymbolThe name will not change
  • useSymbolLiteral to get the identifiersymbolObject, that is, add one before the identifier#symbol
  // Get the symbol object
  var sym1 = Symbol('name');
  print(sym1);   // Symbol("name")

  // the # id is created
  var sym2 = #titan;
  print(sym2);   // Symbol("titan")
Copy the code

Set

  • A collection of objects, each of which appears only once,ListAn object can appear more than once
  • When iterating over elements in a Set, it can be either unordered or ordered at some point. Such as:
    • HashSetIs unordered, which means that the order of its iterations is indeterminate
    • LinkedHashSetIterate over elements in the order they are inserted
    • SplayTreeSetIterate over elements in sort order
  • SetExcept creation mode andListNo, the other properties and methods are basically the same

Create a Set

  // Create an empty Set.
  var set1 = Set(a);print(set1);   / / {}

  // Create a Set containing all elements
  var set2 = Set.from([1.2.3]);
  print(set2);   / / {1, 2, 3}

  // Create an empty Set with strictly equal elements
  var set3 = Set.identity();
  print(set3);   / / {}
Copy the code

methods

  // set2 = {1, 2, 3}
  // Return a new Set that is the intersection of this and other
  var set4 = Set.from([2.3.5.6]);
  print(set2.intersection(set4));  / / {2, 3}

  // Return a new Set containing all elements of this and other (union)
  print(set2.union(set4));  // {1, 2, 3, 5, 6}

  // Check if the Set contains an object, return the object if it does, return null if it does not
  print(set4.lookup(5));   / / 5
  print(set4.lookup(21));  // null
Copy the code

Refer to Dart Data Type 01 for Set and Flutter development for additional properties

Duration

  • DurationRepresents the time difference from one point in time to another
  • If it’s a later time and an earlier time,DurationIt could be negative

Create the Duration

// a unique constructor creates a Duration object
Duration({int days: 0.int hours: 0.int minutes: 0.int seconds: 0.int milliseconds: 0.int microseconds: 0})

// It can be created with one or more of the parameters
// Just use one of the arguments
Duration ration = Duration(days: 1);
print(ration);  / / 24:00:00.000000
Duration ration1 = Duration(hours: 10);
print(ration1);  / / 10:00:00. 000000

// Just use two of the arguments
Duration ration2 = Duration(days: 1, hours: 3);
print(ration2);  / / 27:00:00.000000

// Use all parameters
Duration ration3 = Duration(days: 2, hours: 2, minutes: 23, seconds: 34, milliseconds: 56, microseconds: 89);
print(ration3);  / / has: 34.056089
Copy the code

Relevant operation

  Duration time1 = Duration(days: 1, hours: 1, minutes: 1, seconds: 1, milliseconds: 1, microseconds: 1);
  Duration time2 = Duration(days: 2, hours: 2, minutes: 2, seconds: 2, milliseconds: 2, microseconds: 2);
  print(time1);  / / 25:01:01.001001
  print(time2);  / / 50:02:02.002002

  / / add
  print(time1 + time2);  / / 75:03:03. 003003
  / /
  print(time1 - time2);  / / - 25:01:01.001001
  / / by
  print(time1 * 2);    / / 50:02:02.002002
  // Divide (round)
  print(time2 ~/ 3);  / / 16:40:40. 667334

  / / to compare
  print(time1 > time2);  //false
  print(time1 >= time2);  //false
  print(time1 == time2);  //false
  print(time1 < time2);  //true
  print(time1 <= time2); //true

  // take the opposite value
  print(-time1);  / / - 25:01:01.001001
  print(-(time1 - time2));  / / 25:01:01.001001
Copy the code

Correlation function

  Duration time3 = -Duration(days: 1, hours: 1, minutes: 1, seconds: 1, milliseconds: 1, microseconds: 1);
  print(time3);  / / - 25:01:01.001001

  // take the absolute value
  print(time3.abs());  / / 25:01:01.001001

  // Compare, return value 0: equal, -1: time1 < time2, 1: time1 > time2
  print(time1.compareTo(time2));  / / 1

  // It is a string of characters
  print(time1.toString());
Copy the code

DateTime

  • Represents a point in time
  • Created by constructor or parsing formatted stringDateTimeObject, and matchesISO 8601A subset of the standard, the hour is 24-hour and ranges from 0 to 23
  • DateTimeOnce created, objects are immutable and cannot be modified
  • DateTimeObject uses the local time zone by default unless explicitly specifiedUTCThe time zone

Creation point

  // The current time
  var date1 = new DateTime.now();
  print(date1);  / / the 16:43:15 2019-02-23. 505305

  // Construct a DateTime specified as the local time zone
  //DateTime(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])
  var date2 = new DateTime(2018.10.3.12.23.34.562.1002);
  print(date2);  / / the 12:23:34 2018-10-03. 563002

  // Create in microseconds
  var date3 = new DateTime.fromMicrosecondsSinceEpoch(1000222);
  // isUtc: true: indicates the UTC time zone. The default is false
  var date31 =  new DateTime.fromMicrosecondsSinceEpoch(1000222, isUtc: true);
  print(date3);  / / the 08:00:01 1970-01-01. 000222

  // Create in milliseconds
  var date4 = new DateTime.fromMillisecondsSinceEpoch(1000222);
  // isUtc: true: indicates the UTC time zone. The default is false
  var date41 = new DateTime.fromMillisecondsSinceEpoch(1000222, isUtc: true);
  print(date4);  / / the 08:16:40 1970-01-01. 222
  
  // Specifies the time in the UTC time zone
  var date5 = new DateTime.utc(1969.7.20.20.18.04);
  print(date5);  / / the 1969-07-20 20:18:04. 000 z
Copy the code

parse

DateTime parse(String formattedString)
Copy the code
  • Based on the time string, createDateTime
  • If the input string cannot be parsed, an exception is thrown
  • The string currently accepted is:
    • Date: a 4-6 digit year, a 2-digit month, a 2-digit number
      • Year, month and day are optional to separate from each other
      • For example: “19700101”, “-0004-12-24”, “81030-04-01”
    • The time section is optional from the dateTOr a space to separate
      • For the time part, include 2-digit hours, then 2-digit minutes value optional, then 2-digit seconds value optional, and then.Optional add 1-6 digit number of seconds
      • Minutes and seconds work:separated
      • For example: “12”, “12:30:24.124”, “123010.50”
    • The time zone offset is optional and may be separated from the previous portion by a space
      • Time zone iszorZ, or a two-digit hour portion with a plus or minus, and an optional two-digit minute portion
      • The symbol must be+or-“And cannot be omitted
      • Minutes and hours may be used:separated
  • Examples of accepted strings:
    • "The 2012-02-27 13:27:00"
    • "The 2012-02-27 13:27:00. 123456 z"
    • "20120227 13:27:00"
    • "20120227T132700"
    • "20120227"
    • "+ 20120227"
    • "2012-02-27T14Z"
    • "2012-02-27T14+00:00"
    • "-123450101 00:00:00 Z": The year is -12345
    • "2002-02-27T14:00:00-0500"And:"2002-02-27T19:00:00Z"The same
  // Format the time string
  var date6 = DateTime.parse("The 2012-02-27 13:27:00");
  var date7 = DateTime.parse('20120227T132700');
  print(date6);  / / the 13:27:00 2012-02-27. 000
  print(date7);  / / the 13:27:00 2012-02-27. 000
Copy the code

Attribute values

  var time = DateTime.parse("The 2019-02-25 13:27:04");
  // Get year-month-day-week
  print(time.year);   / / 2019
  print(time.month);  / / 2
  print(time.day);    / / 25
  print(time.weekday);/ / 1

  // Get time - minute - second - millisecond - microsecond
  print(time.hour);       / / 13
  print(time.minute);     / / 27
  print(time.second);     / / 4
  print(time.millisecond);/ / 0
  print(time.microsecond);/ / 0

  // Is the UTC time zone
  print(time.isUtc);
  
  // 1970-01-01t00:00:00 Z (UTC) The number of microseconds that have passed since the start
  print(time.microsecondsSinceEpoch);

  //1970-01-01T00:00:00Z (UTC) Number of milliseconds since the start
  print(time.millisecondsSinceEpoch);
  
  // The time zone name provided by the platform
  print(time.timeZoneName);

  // Time zone offset, the time difference between local time and UTC
  print(time.timeZoneOffset);
Copy the code

Correlation function

  // Get the current time
  DateTime today = new DateTime.now();
  print(today);  / / the 11:18:16 2019-02-28. 198088

  // Add duration to return a new DateTime instance
  DateTime newDay = today.add(new Duration(days: 60));
  print(newDay);  / / the 11:18:16 2019-04-29. 198088

  // Subtract duration to return a new DateTime instance
  DateTime newDay1 = today.subtract(new Duration(days: 60));
  print(newDay1);  / / the 11:25:31 2018-12-30. 741382

  // Compare the size of two time values, 0: equal, -1: before < after, 1: before > after
  var isCom = today.compareTo(newDay);
  print(isCom);  // -1

  // Calculate the difference between the two times
  Duration duration = today.difference(newDay);
  print(duration);  / / - 1440:00:00. 000000

  // Compare two times
  print(today.isAfter(newDay));  // false
  print(today.isBefore(newDay)); // true

  // Compare whether it is the same time
  print(today.isAtSameMomentAs(newDay));  //false

  // Returns the value of this DateTime in the local time zone
  print(today.toLocal());  / / the 11:30:51 2019-02-28. 713069
Copy the code

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!