之前的文章 、 讲解了dart语言的数据类型和运算符,这里继续讲解语法部分。
函数(Function)
一、基本形式
① 形式一
返回值类型 函数名(参数类型 形式参数)
{
// 执行语句
return 返回值
}
例:
String foo(String name, int age, double score)
{
if (score < 60) {
return "$name的分数是$score,不及格";
}
return "$name的分数是$score, 及格";
}
② 形式二
返回值类型 函数名(参数类型 形式参数) => 表达式;
例:
String foo(String name, double score) => score < 60 ? "$name的分数是$score,不及格" : "$name的分数是$score,及格";
二、可选参数和默认值
① 将可选参数放到中括号中[]
② 使用等号=设置默认值
③ 默认值可以是numbers、String、Map、List
④ 必须使用const修饰Map、List默认值
例:
void foo(String name, [int age = 18, double score = 80.0]) {
print("$name的分数是$score");
}
void foo(String name,
[Mapscores = const {"math": 60.0, "english": 60.0}]) {
print("");
}
void foo(String name, [Listscores = const [64.9, 59.0, 89.0]]) {
print("");
}
三、函数也是对象(object)
dart是真正的面向对象语言,一切都是对象,函数也是对象,因此可以将函数赋值给一个变量。这一点和javascript有些相似。
例:
static void foo(String name, [Listscores = const [64.9, 59.0, 89.0]]) {
print("");
}
// 将函数赋值给变量
var f = foo;
四、函数可以用作形式参数
例:
void foo(String name,
[Listscores = const [64.9, 59.0, 89.0]]) {
print("");
}
void foo1(Function foo) {
}
// 调用foo1函数
// foo用作形式参数
foo1(foo);
五、匿名函数(Anonymous Functions)
我们可以定义没有没有函数名称的函数,在实际程序开发中经常使用。
void (参数)
{
}
例:
var list = [33, 48, 29];
list.forEach((index) {
print(index);
});
六、静态作用域(Lexical Scope)
函数具有静态作用域、大括号{}之外的区域,无法使用大括号{}内定义的变量。
例:
void foo() {
var name = “Mr. Hao”;
}
// 使用name会报错
print(name);
七、类函数、实例函数
类函数也称作静态函数,可以使用类名称调用的函数,使用static修饰
例:
static void foo(String name, [Listscores = const [64.9, 59.0, 89.0]]) {
print("");
}
流程控制(Control flow statements)
一、条件
① if else
例:
bool flag = true;
if (flag == true) {
// 如果flag是true
} else {
// 如果flag是false
}
② switch case
例:
double score = 39;
switch (score) {
case 50:
print("不及格");
break;
case 60:
print("及格");
break;
case 100:
print("满分");
break;
default:
print("未知");
}
二、循环
① for循环
例:
for (var i = 0; i < 10; i++) {
print(i);
}
var list = [33, 48, 29];
for (var i in list) {
print(i);
}
② while、do while
bool flag = true;
while(flag) {
// 执行语句
}
bool flag = true;
do {
// 执行语句
} while (flag);
三、其他
另外断言(Assert)(生产模式不执行)、异常(Exceptions)、抛出异常(Throw)、捕获异常(Try Catch Finally)也可以影响程序执行流程。
结语
基本语法都较为简单,大家可以用两周时间快速的练习掌握,然后尽快投入到实际开发中去,比如使用dart开发web应用、移动应用或者是后端服务等。
欢迎转发,欢迎收藏,欢迎关注『郝先生谈技术』
閱讀更多 郝先生談技術 的文章
關鍵字: Numbers 移动互联网 JavaScript