1. Variable declaration
How to define variables
var name = 'Bob';
Initial value of variable
int lineCount;
assert(lineCount == null ); // Variables (even numbers) are initially null.
You can use var or specify the type directly.
final, a variable defined as final, the value cannot be changed
final name = 'Bob'; // Or: final String name = 'Bob';
name = 'Alice'; // ERROR
2. Basic type
String
Strings can use single quotes or double quotes.
var s1 = 'Single quotes work well for string literals. ';
var s2 = "Double quotes work just as well.";
In a string, you can apply the value directly, ${expression}, if it's just a variable , you can remove {}
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. $ {s.toUpperCase()} is very handy!' ==
'That deserves all caps. STRING INTERPOLATION is very handy!');
Multi-line string, will Considered the default splice.
var s = 'String ''concatenation'
" works even over line breaks.";
assert(s == 'String concatenation works even over line breaks.');
If you want to use a multi-line string, you can do this, use '''
var s1 = '''
You can create
multi-line strings like this one.
''';
Create one Do not consider escaped strings
var s = @" In a raw string, even n isn't special.";
StringBuffer, very similar to that in .net.
var sb = new StringBuffer();
sb.add("Use a StringBuffer ");
sb.addAll(["for ", "efficient ", "string ", "creation "]);
sb.add("if you are ").add("building lots of strings.");
var fullString = sb.toString();
Numbers
There are mainly two types, int and double, they both inherit the num type
Conversion between numbers and strings
// String -> int
var one = Math.parseInt("1");
assert(one == 1);
// String -> double
var onePointOne = Math.parseDouble("1.1");
assert(onePointOne == 1.1);
// int -> String
var oneAsString = 1.toString();
assert(oneAsString == "1");
// double -> String
var piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == "3.14");
Boolean type
bool, different from js, as long as it is not true, it is false.
Lists (can be used as an array)
var list = [1,2,3]; / /Instantiate a list
list.add(4); //Add an element 4
You can use for, for...in, foreach() to traverse a list.
var list = [1,2,3];
for (final x in list) {
print(x);
}
or
var list = [1,2,3];
list.forEach((element) => print(element));
Maps (dictionary type)
var gifts = { // Keys Values
"first" : "partridge",
"second" : "turtledoves",
"fifth" : "golden rings"};
gifts["third"] = "apple"; //Add a
Use foreach to traverse
var gifts = {
"first" : "partridge",
"second": "turtledoves",
"fifth" : "golden rings"};
gifts.forEach((k,v) => print( '$k : $v'));
getKeys() and getValues() methods
var gifts = {"first": "partridge", "second": "turtledoves"};
var values = gifts.getValues();
//Print partridge and turtledoves, but not necessarily in that order.
values.forEach((v) => print(v));