Dart language foundation of Flutter Getting Started Guide

1, Basic chapter 1.1 advantages of dart language ...
1, Basic chapter

1, Basic chapter

1.1 advantages of dart language

Advantages of Dart language

1. AOT compilation and JIT compilation are supported

2. Dart is a single thread and preemption is not allowed.

TODO: learn more about AOT and JIT

1.2 basic syntax of dart language

Variable declaration

1. You can define variables through var and support closures

2. Dart is a strongly typed language, which automatically deduces the type, and the variable type cannot be changed.

3. Variables that are not initialized will be given a default value of null

4. Constant declaration: const, final. The difference is

  • const compile time constant must be initialized at declaration time, and the initialization value must be a determined value without calculation.
  • final runtime constant, initialization at declaration / constructor initialization, and the value can be calculated dynamically.
Basic type

number,String,bool,list,map,set

number

  • The number type only has Int and double.
num x = 1; // x can have both int and double values x += 2.5;
  • String to number: int.parse(), double.parse()

  • Number to string: intNum.toString(), doublenum. Tostrinasfixed (n) keep N decimal places.

// String -> int var one = int.parse('1'); assert(one == 1); // String -> double var onePointOne = double.parse('1.1'); assert(onePointOne == 1.1); // int -> String String oneAsString = 1.toString(); assert(oneAsString == '1'); // double -> String String piAsString = 3.14159.toStringAsFixed(2); assert(piAsString == '3.14');

Strings

  • Use variables in strings, wrapped with ${} / $variables
var s = 'string interpolation'; assert('Dart has $s, which is very handy.' == 'Dart has string interpolation, ' 'which is very handy.'); assert('That deserves all caps. ' '$ is very handy!' == 'That deserves all caps. ' 'STRING INTERPOLATION is very handy!');
  • '...' ','... ', indicates a multiline string
var s1 = ''' You can create multi-line strings like this one. '''; var s2 = """This is also a multi-line string.""";
  • r '...', r '...' means "raw" string TODO

Bool value

Dart is a strong bool type check. It is considered true only if the value of bool type is true

List list

Create, add, delete, query and sort

  • Create list

    1,new List

    2. Simple List

    3. Set if and set for

// 1,new List var vegetables = new List(); // 2. Simply use List to assign values var fruits = ['apples', 'oranges']; var constantList = const [1, 2, 3];// Constant list // constantList[1] = 1; // This line will cause an error.
// 3. Set if var nav = [ 'Home', 'Furniture', 'Plants', if (promoActive) 'Outlet' ]; // 3. Set for var listOfInts = [1, 2, 3]; var listOfStrings = [ '#0', for (var i in listOfInts) '#$i' ]; assert(listOfStrings[1] == '#1')
  • Add element

Dart 2.3 adds the extension operator... And the expansion operator?

var list = [1, 2, 3]; var list2 = [0, ...list]; assert(list2.length == 4); var list; var list2 = [0, ...?list]; assert(list2.length == 1);

Methods of adding elements: add() adds one element and addAll() adds multiple elements

// Add element fruits.add('kiwis'); // Add multiple elements fruits.addAll(['grapes', 'bananas']);
  • Delete element
// Delete the element at the specified position and return the deleted element fruits.removeAt(index); // If the specified element is deleted, true is returned for success and false is returned for failure fruits.remove('apples'); // Delete the last element and return the deleted element fruits.removeLast(); // Delete the specified range element, including header but not tail. null will be returned if successful fruits.removeRange(start,end); // Delete the element of the specified condition and return null successfully fruits.removeWhere((item) => item.length >6); // Delete all elements fruits.clear();
  • Query element
// Get the first element fruits.first; // Gets the last element of the element fruits.last; // Find the index number of an element assert(fruits.indexOf('apples') == 0);
  • sort
// sort() sorts the elements and passes in a function as a parameter. Return < 0 means from small to large, and > 0 means from large to small fruits.sort((a, b) => a.compareTo(b));

Set

Unique unordered set.

  • Create Set
// 1. Simple assignment var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'}; //Note that var names = {}; This creates a map, not a set! // 2, var names = <String>{}; Set<String> names = {};
  • Add elements add and addAll to Set
  • Judge whether the Set contains an element: set.contains(item)
//Include _saved.contains(pair); //remove _saved.remove(pair);

Map

  • Create Map
// Declaration of Map var hawaiianBeaches = { 'oahu' : ['waikiki', 'kailua', 'waimanalo'], 'big island' : ['wailea bay', 'pololu beach'], 'kauai' : ['hanalei', 'poipu'] }; var searchTerms = new Map(); // Specifies the parameter type of the key value pair var nobleGases = new Map<int, String>(); // For the assignment of Map, the Key is in brackets, which is not an array nobleGase[54] = 'dart'; //Key value pairs in the Map are unique //Unlike Set, if the Key entered for the second time exists, the Value will overwrite the previous data nobleGases[54] = 'xenon'; assert(nobleGases[54] == 'xenon'); // Retrieve whether the Map contains a Key assert(nobleGases.containsKey(54)); //Delete a key value pair nobleGases.remove(54); assert(!nobleGases.containsKey(54));
function

Return value type before function

bool isNoble ( int atomicNumber ) { return _nobleGases [ atomicNumber ] != null ; } isNoble ( atomicNumber ) { return _nobleGases [ atomicNumber ] != null ; } bool isNoble ( int atomicNumber ) => _nobleGases [ atomicNumber ] != null ;

parameter

Function parameters can be followed by named parameters and optional positional parameters (but not both).

Named parameters

Function parameters are named. When passing parameters, you need to specify which data to pass to which parameters.

// Function definition void enableFlags() {...} // function call enableFlags(bold: true, hidden: false);

required must pass a parameter

Optional location parameters

Optional location parameter. Use [] to wrap the parameter. This location parameter can not be transferred.

String say(String from, String msg, [String? device]) { var result = '$from says $msg'; if (device != null) { result = '$result with a $device'; } return result; }

Parameter defaults

void enableFlags() {...}
Conditional judgment and circulation
  • if...else
  • for
  • while do-while
  • break continue
  • switch... Case if there is an expression after the case but no break, an exception will be thrown
  • assert (valid only in checked mode). If the condition is false, an exception is thrown

if - else

The judgment value must be true or false, and cannot be anything else!

for loop

var message = StringBuffer('Dart is fun'); for (var i = 0; i < 5; i++) { message.write('!'); }
var collection = [1, 2, 3]; collection.forEach(print); // 1 2 3
asynchronous

Future,async/await

Future

Similar to Promise, execute then successfully, catchrror if failed, and whenComplete anyway

void main() { Future.delayed(new Duration(seconds: 1), () { return "666"; }).then((data) { // Execute after success print(data); }).catchError((e) { // Execute after failure print("error"); }).whenComplete(() { // It will be executed regardless of success or failure print("complete"); }); }

async/await

Add async after function ()

void main() async{ print(await getString()); } getString() { return Future.delayed(new Duration(seconds: 1), () { return "666"; }); }

7 October 2021, 03:44 | Views: 7681

Add new comment

For adding a comment, please log in
or create account

0 comments