Dart语言快速学习上手(新手上路)

时间:2021-05-12 05:37:33

Dart语言快速学习上手(新手上路)

// 声明返回值
int add(int a, int b) {
return a + b;
} // 不声明返回值
add2(int a, int b) {
return a + b;
} // =>是return语句的简写
add3(a, b) => a + b; //命名参数、位置参数、参数默认值 sayHello({String name}) {
print("hello, my name is $name");
} sayHello2({name: String}) {
print("hello, my name is $name");
} //位置参数
sayHello(String name, int age, [String hobby]) { // 位置参数可以有多个,比如[String a, int b]
StringBuffer sb = new StringBuffer();
sb.write("hello, this is $name and I am $age years old");
if (hobby != null) {
sb.write(", my hobby is $hobby");
}
print(sb.toString());
} // 命名参数的默认值
int add({int a, int b = 3}) { // 不能写成:int add({a: int, b: int = 3})
return a + b;
} // 位置参数的默认值
int sum(int a, int b, [int c = 3]) {
return a + b + c;
} //函数作为一类对象 printNum(int a) {
print("$a");
} //将一个函数赋值给某个变量
printNum(int a) {
print("$a");
} //匿名函数 test(Function callback) {
callback("hello");
} // void main() { print("hello world!"); var a = 1;
int b = 10;
String s = "hello";
dynamic c = 0.5; var count = 10;
final Num = count; // final 只能赋值一次
const Num1 = 10; // const赋值必须是编译时常量 // numbers
var a = 0;
int b = 1;
double c = 0.1; // strings
var s1 = 'hello';
String s2 = "world"; // booleans
var real = true;
bool isReal = false; // lists
var arr = [1, 2, 3, 4, 5];
List<String> arr2 = ['hello', 'world', "123", "456"];
List<dynamic> arr3 = [1, true, 'haha', 1.0]; // maps
var map = new Map();
map['name'] = 'zhangsan';
map['age'] = 10;
Map m = new Map();
m['a'] = 'a'; //runes,Dart 中 使用runes 来获取UTF-32字符集的字符。String的 codeUnitAt and codeUnit属性可以获取UTF-16字符集的字符
var clapping = '\u{1f44f}';
print(clapping); // 打印的是拍手emoji的表情 // symbols
print(#s == new Symbol("s")); // true print(add(1, 2)); // 3
print(add2(2, 3)); // 5
print(add3(1, 2)); // 3 // hello, this is zhangsan and I am 20 years old
sayHello("zhangsan", 20);
// hello, this is zhangsan and I am 20 years old, my hobby is play football
sayHello("zhangsan", 20, "play football"); // 依次打印:
// 1
// 2
// 3
var arr = [1, 2, 3];
arr.forEach(printNum); var f1 = printNum;
Function f2 = printNum;
var f3 = (int a) => print("a = $a");
f1(1);
f2(2);
f3(6); test((param) {
// 打印hello
print(param);
}); }