Variable declaration
Once a VAR variable in var Dart is assigned, the type is determined and cannot be changed
object art The root class of all objects, that is, all types are subclasses of Object (including Function and Null)
-
dynamic declares variables that can be assigned to any object. dynamic is the same as Object in that they declare variables that can change the type of assignment later.
The object compiler declared by dynamic provides all possible combinations, while the object declared by Object can only use Object's properties and methods, otherwise the compiler will error
-
Final and const If you never intend to change a variable, use final or const.
The difference is that the const variable is a compile-time constant and the final variable is initialized the first time it is used.Variable modified by final or const, variable type can be omitted
function
-
Function declaration
Dart function declarations are treated as dynamic s by default when return value types are not explicitly declared. Note that function return values have no type inference:
bool isNoble(int atomicNumber) { return _nobleGases(atomicNumber) != null; }
-
Short form syntax can be used for functions that contain only one expression
bool isNoble (int atomicNumber )=> _nobleGases [ atomicNumber ] != null ;
-
Function as variable
var say = (str){ print(str); }; say("hi world");
-
Functions are passed as parameters
void execute(var callback) { callback(); } execute(() => print("xxx"))
-
Optional location parameters
Wrap a set of function parameters marked with [] as optional location parameters:
String say(String from, String msg, [String device]) { var result = '$from says $msg'; if (device != null) { result = '$result with a $device'; } return result; }
-
Optional Named Parameters
When defining a function, use {param1, param2,...}, which specifies named parameters.For example:
//Set [bold] and [hidden] flags void enableFlags({bool bold, bool hidden}) { // ... }
When calling a function, you can use the specified named parameters.For example: paramName: value
enableFlags(bold: true, hidden: false);
Asynchronous Support
Future
Meaning: It is used to handle asynchronous operations. Successful asynchronous processing executes successful operations. Failed asynchronous processing captures errors or stops subsequent operations.A Future corresponds to only one result, either successful or failed.
Future.then
Future.catchError
Future.whenComplete
Future.delayed(new Duration(seconds: 2),(){ //return "hi world!"; throw AssertionError("Error"); }).then((data){ //Success will come here print(data); }).catchError((e){ //Failure to execute will come here print(e); }).whenComplete((){ //Success or failure will come here });
- Future.wait.
It accepts a Future array parameter and triggers a successful callback for the n only if all Futures in the array execute successfully. An error callback is triggered whenever a Future executes unsuccessfully.
Future.wait([ // Return results in 2 seconds Future.delayed(new Duration(seconds: 2), () { return "hello"; }), // Return results in 4 seconds Future.delayed(new Duration(seconds: 4), () { return " world"; }) ]).then((results){ print(results[0]+results[1]); }).catchError((e){ print(e); });
Async/await
Callback Hell
//Define each asynchronous task separately Future<String> login(String userName, String pwd){ ... //User Login }; Future<String> getUserInfo(String id){ ... //Get user information }; Future saveUserInfo(String userInfo){ ... // Save user information }; login("alice","******").then((id){ //Get user information via id after successful login getUserInfo(id).then((userInfo){ //Save after getting user information saveUserInfo(userInfo).then((){ //Save user information and do other things next ... }); }); })
- Eliminate Callback Hell with Future
```dart login("alice","******").then((id){ return getUserInfo(id); }).then((userInfo){ return saveUserInfo(userInfo); }).then((e){ //Perform the next action }).catchError((e){ //error handling print(e); }); ``` > *"Future All API The return value of is still a Future Object, so it's easy to make chain calls"* ,If then Returned in is a`Future`If so, the`future`Will execute, after execution will trigger the following`then`Callback, which goes down in turn, avoids layer by layer nesting.
- Eliminate callback hell using async/await
```da task() async { try{ String id = await login("alice","******"); String userInfo = await getUserInfo(id); await saveUserInfo(userInfo); //Perform the next action } catch(e){ //error handling print(e); } } ``` - `async`Used to indicate that a function is asynchronous, the defined function returns a`Future`Object, you can use then Method adds a callback function. - `await` Followed by a`Future`,Indicates waiting for the asynchronous task to complete before going down;`await`Must appear in `async` Function interior.
steam
Stream is also used to receive asynchronous event data, unlike Future, which can receive the results of multiple asynchronous operations (success or failure).That is, when performing an asynchronous task, you can pass result data or error exceptions by triggering success or failure events multiple times.Stream is commonly used in asynchronous task scenarios where data is read multiple times, such as network content downloads, file reads and writes, etc.
Stream.fromFutures([ // Return results in 1 second Future.delayed(new Duration(seconds: 1), () { return "hello 1"; }), // Throw an exception Future.delayed(new Duration(seconds: 2),(){ throw AssertionError("Error"); }), // Return results in 3 seconds Future.delayed(new Duration(seconds: 3), () { return "hello 3"; }) ]).listen((data){ print(data); }, onError: (e){ print(e.message); },onDone: (){ }); //output //I/flutter (17666): hello 1 //I/flutter (17666): Error //I/flutter (17666): hello 3
Reprinted from https://book.flutterchina.club/chapter1/dart.html