Dart Basics - common data types and functions

Posted by barbatruc on Fri, 14 Jan 2022 14:30:03 +0100

function

The declaration method is similar to OC. It's just that you don't need to add * when labeling formal parameter types. After each sentence is written, you need to add *;

void thisIsDartFunction(int parma) {
	print('hello dart');
}

Parameter type:

  • Required parameters
  • Optional parameters
    Write after required parameters
    Wrap in brackets
    Optional parameters with default values
  • Named parameters
    Wrap it in braces
    When calling, the parameter name is consistent with the name in the declared function
  • Function parameters
// Required
String user1(String name) {
}
// Optional dynamic without assignment
String user2(String name, [dynamic age]) {
}

String user3(String name, [int age = 10]) {
}
// Named parameters
String user4(String name, {int age = 10}) {
}

void main() {
	user1('1');
	user2('2', 18);
	user3('3', 18);
	user4('4', age: 18);	
}

Asynchronous function

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'dart:convert';

// Future getIPAddress() {
//   final url = 'https://httpbin.org/ip';
//   return http.get(url).then((response) {
//     print(response.body);
//   });
// }

Future getIPAddress() async {
  final url = 'https://httpbin.org/ip';
  final res = await http.get(url);
  String ip = jsonDecode(res.body)['origin'];
  return ip;
}
// void main() {
//   getIPAddress()
//       .then((value) => print(value))
//       .catchError((error) => print(error));
// }

void main() async {
  try {
    final ip = await getIPAddress();
    print(ip);
  } catch (err) {
    print(err);
  }
}

variable

The declaration method is similar to swift and oc. Use var to indicate that the variable is variable, or directly and explicitly declare the variable data type.

void thisIsDartFunction(int parma) {
	var page = 0;
	print('read to $page');
}
  • Specify the execution type: int age = 11;
  • Implicit declaration type: var age = 11; Or dynamic age = 11;
  • Variable names are case sensitive. Age and age are two variables
  • The default value of the variable is null (the default value of the variable in js is undefined)
  • The value of a dart variable is not implicitly typed (from int to string)

constant

  • Declared constant:
  1. const age = 11;
  2. final age = 11;

The difference between const and final: the runtime value can be assigned to the variable modified by final. Cannot be assigned to a variable modified by const. Const can only modify the value determined at compile time.
Example: final time = datetime now();

data type

Number, String, List, Boolean, Set, Map, other

  • Number

    int count = 3;
    double price = 11.1;
    // num type, including int and double types
    num x = 1.11;
    print(x.toString());  //  1.11
    print(1.11.toInt());  //  1
    // rounding
    print(1.23456.round());  //  1
    print(1.23456.toStringAsFixed(4));  //  1.2346
    // Surplus
    print(10.remainder(4));  // 2
    // Number comparison: 0 is the same, 1 is greater than - 1 is less than
    print(10.compareTo(12));  // -1
    // Returns the maximum common divisor
    print(12.gcd(18));	// 6
    // Scientific counting method
    print(1000.toStringAsExponential(1));	// 1.0e+3
    // Judge non numeric NaN
    print(x.isNaN);
    
  • String

    • String declaration: single quotation mark, double quotation mark and three quotation marks (with newline characters)

    • Common API s:
      https://api.dart.cn/stable/2.13.4/dart-core/String-class.html

    • regular expression

      RegExp(r 'regular expression')
      For example: RegExp(r '\ d +')

    • Common basic API s

      String str1 = 'hello';
      String str2 = " world";
      String str3 = '''hello 
      world''';
      
      print(str1);  // hello
      print(str2);  //  world
      print(str3);  // hello 
      				//world
      
      // Splicing
      print(str1 + str2); // hello world
      // Template string
      print('$str1 $str2'); // hello world
      // String segmentation 
      str1.split('l'); // [he, o]
      // String trimming (without spaces)
      '	space	'.trim(); // space
      // Determine whether the string is empty
      ''.isEmpty; // true
      ''.isNotEmpty; // false
      // String substitution
      str1.replaceAll('h', 'H'); // Hello
      // String regular replacement
      '1a1b1c1d'.replaceAll(RegExp(r'\d+'), ''); // 1111
      // String regular matching
      var isPhone = RegExp(r'^1\d{10}$');
      print(isPhone.hasMatch('13322223333')); // true
      print(isPhone.hasMatch('1332222333')); // false
      // Find string
      str1.contains('l') // true
      // Returns the first matched subscript
      str1.indexOf('h') // 0
      
  • Boolean
    Boolean types only have true and false
    When judging variables, express Boolean values explicitly

    if (name == null) { }
    if (age == 0) { }

  • List

    • Common API
      https://api.dart.cn/stable/2.13.4/dart-core/List-class.html

    • Common basic API s

      // Create List
      // Literal mode
      List list = [];
      // Literal -- Generic
      List list = <String>[];
      // Extend operator
      var list = [1, 2, 3];
      var list2 = [0, ...list];
      // Constructor Declaration -- the named parameter growable identifies whether an empty array is mutable
      var list3 = new List.empty(growable: true);
      list3.add(1); // [1]
      var list4 = new List.filled(3, 6); // [6, 6, 6]
      
      // extend
      var list5 = [0, ...list4]; // [0, 6, 6, 6]
      var list6;
      // Judge before expand - avoid warnings
      var list 7 = [0, ...?list6]; // [0]
      // list length
      list5.length // 4
      // Get the flipped list
      var list8 = list5.reversed.toList(); // [6, 6, 6, 0]
      // Add element
      list5.addAll([9, 3]); // [0, 6, 6, 6, 9, 3]
      // Delete element directly
      list5.remove(3); // [0, 6, 6, 6]
      // Delete element by subscript
      list5.removeAt(4); // [0, 6, 6, 6, 3]
      // Insert an element
      list5.insert(4, 9); // [0, 6, 6, 6, 9, 3]
      // Insert multiple elements
      list5.insert(4, [8, 9]); // [0, 6, 6, 6, 8, 9, 3]
      // list empty
      list5.clear(); // []
      // Merge elements
      List dartList = ['aaa', 'sss'];
      dartList.join('') // aaasss
      
    • List traversal

      • forEach()
        Traversal list
      • map()
        Traverse the list and process the elements, generate a new list and return
      • where()
        Return data that meets the conditions
      • any()
        Return true as long as one of the conditions is met
      • every()
        Judge whether each item meets the conditions and return true

      Common for i + + and for in can also be traversed.

      var list1 = [1, 2, 3];
      var list2 = list1.map((element) {
      	return element * element;
      }).toList(); // [1, 4, 9]
      var list3 = list1.map((element) => element * element;).toList(); // [1, 4, 9]
      // Array extension
      int list4 = [[1, 1], [3, 4]];
      var list5 = list4.expand((element) => element).toList(); // [1, 1, 3, 4]
      
      
    • Set

      • An unordered and unique collection of elements that cannot be evaluated by subscript
      • You can find intersection, union, difference, etc
      • Common basic API s:
      // Literal 
      var nums = <int>{1, 2, 3};
      var fruits = new Sets();
      fruits.add('apple');
      fruits.add('orange');
      // List to set
      List nums = [1, 1, 3, 2];
      nums.toSet();
      // Find intersection
      intersection
      // Union set
      union
      // Difference set
      difference
      // Returns a specific value
      first
      last
      
    • Map

    • Common basic API s

      // Literal 
        var map = {'name': 'Li',
      			   'age': 20};
        // Constructor
        var p = new Map());
        p['name'] = 'Xie';
        p['age'] = 28;
        
        // Check whether the Key exists
        print(p.containsKey('name'));
        // The value is assigned only when there is no key
        p.putIfAbsent('gender', () => 'male');
        // Get all key s
        print(p.keys);
        // Get all value s
        print(p.values);
        // Delete according to condition
        p.removeWhere((key, value) => key == 'gender');
      

function:

dart .dart file path
Note: you must wrap it with the void main() {} function

Topics: Flutter