In this article, we mainly explain the similarities and differences between Dart and JavaScript by using standard JavaScript. If you are not familiar with JavaScript, you can omit the JavaScript part and directly learn the Flutter part.
Program entrance
JavaScript does not have predefined entry functions, but in Dart, each app must have a top-level main () function as the entry point for the application.
// Dart
main() {
}
Copy the code
Practice DartPad.
DartPad is an Online playground for Dart, and Dart Compiler is also available for Dart Online playground.
Console output
To print to the console in Dart, use print:
// JavaScript
console.log("Hello world!");
// Dart
print('Hello world! ');
Copy the code
Practice DartPad.
variable
Dart is type-safe – it uses a combination of static type checking and runtime checking to ensure that the value of a variable always matches the type of the variable’s static value. Although type is required, some type annotations are optional because Dart does type inference.
Create and assign variables
In JavaScript, variable types cannot be defined.
In Dart, variables must be of an explicit type or a type that the system can resolve.
// JavaScript
var name = "JavaScript";
// Dart
String name = 'dart'; // Explicitly typed as a string.
var otherName = 'Dart'; // Inferred string.
// Both are acceptable in Dart.
Copy the code
Practice DartPad.
For more information, see Dart’s Type System.
The default value
In JavaScript, the uninitialized variable is undefined.
In Dart, an uninitialized variable has an initial value of NULL.
Note: Numbers are treated as objects in Dart, so the value of any uninitialized variable with a number type is “NULL.”
// JavaScript
var name; // == undefined
// Dart
var name; // == null
int x; // == null
Copy the code
Try DartPad.
For more information, see the variables section on the Dart website.
Check for null or zero
In JavaScript, the value of 1 or any non-null object is treated as true.
// JavaScript
var myNull = null;
if(! myNull) { console.log("null is treated as false");
}
var zero = 0;
if(! zero) { console.log("0 is treated as false");
}
Copy the code
In Dart, only the Boolean value “true” is treated as true.
// Dart
var myNull = null;
if (myNull == null) {
print('use "== null" to check null');
}
var zero = 0;
if (zero == 0) {
print('use "== 0" to check zero');
}
Copy the code
Practice DartPad.
high energy alert
Dart NULL checks best practices
Starting with Dart 1.12, the null-aware operator is available to help us do null checking:
bool isConnected(a, b) {
booloutConn = outgoing[a]? .contains(b) ??false;
boolinConn = incoming[a]? .contains(b) ??false;
return outConn || inConn;
}
Copy the code
? The operator blocks calls to the right if the left is null. The operator sets the default value for an expression on the left if it is null.
For expressions:
outgoing[a]? .contains(b)Copy the code
If outgoing is null or outgoing[a] is null, or contains(b) is null, the expression is null.
Take a look at the following expected results:
print(null ?? false);
print(false ?? 11);
print(true ?? false);
Copy the code
Practice a practice
Tip: Get the length of an array in an object: searchModel? .data? .length ?? 0.
Functions
Dart is similar to JavaScript functions. The main difference is the declaration:
// JavaScript ES5
function fn() {
return true;
}
// Dart
fn() {
return true;
}
// can also be written as
bool fn() {
return true;
}
Copy the code
Practice DartPad.
Refer to the official DART documentation Functions for more information on functions.
Asynchronous programming
Futures
Like JavaScript, Dart supports single-threaded execution. In JavaScript, the Promise object represents the final completion (or failure) of an asynchronous operation and its resulting value, and Dart uses a Future to represent an asynchronous operation:
// JavaScript
_getIPAddress = (a)= > {
const url="https://httpbin.org/ip";
return fetch(url)
.then(response= > response.json())
.then(responseJson= > {
console.log(responseJson.origin);
})
.catch(error= > {
console.error(error);
});
};
// Dart
_getIPAddress() {
final url = 'https://httpbin.org/ip';
HttpRequest.request(url).then((value) {
print(json.decode(value.responseText)['origin']);
}).catchError((error) = > print(error));
}
Copy the code
Practice: DartPad.
More information about Futures can be found in the DART official documentation Futures.
Async and await
An async function declaration defines an asynchronous function.
In JavaScript, the async function returns a Promise. The await operator is used to await a Promise:
// JavaScript
async _getIPAddress() {
const url="https://httpbin.org/ip";
const response = await fetch(url);
const json = await response.json();
const data = await json.origin;
console.log(data);
}
Copy the code
In Dart, async functions return a Future whose body is to be executed later. The await operator is used to wait for the Future:
// Dart
_getIPAddress() async {
final url = 'https://httpbin.org/ip';
var request = await HttpRequest.request(url);
String ip = json.decode(request.responseText)['origin'];
print(ip);
}
Copy the code
Practice DartPad.
More information about Futures can be found in the OFFICIAL DART documentation async and await.
For more practical tips and best practices on basic Dart knowledge, learn How to develop Ctrip App with Flutter1.x.
To be continued
- The basics of Flutter
- Flutter theme and word processing
- Flutter what is a declarative UI
- Flutter layout and list
- Flutter gesture detection and touch event processing
- Management of Flutter state D
- Flutter threads and asynchronous UI
- Flutter form input with rich text
- Flutter Awareness view md
- Flutter invokes hardware, third-party services, and platform interactions and notifications
- Flutter routing and navigation
- Flutter project structure, resources, dependencies, and localization
reference
- Flutter from entry to advanced practice