首页 扑波教程

飞镖基础知识

介绍Dart编程语言的基础知识,用于使用Flutter SDK用于移动,Web和超越的浮动SDK。

4.7/5 40次评级

版本

  • 飞镖2,Flutter,Dartpad

你想要开始 发展,但只发现扑腾使用了 编程语言?本教程将向您介绍一些DART基础知识,因此您可以通过语言启动和运行扑腾开发。

镖于2011年由Google发布,最初被设计为JavaScript的替代品。从那以后,为iOS,Android和Web开发的浮动SDK发布已在DART语言上放置了一个新的聚光灯。此录制时最新版本的DART是2.4。

镖与其他语言有许多相似之处,您可能已经熟悉,例如Java,C#,Swift和Kotlin。 Dart具有以下语言特征:

  • 静态打字
  • 类型推断
  • 字符串表达式
  • 多范式包括OOP和功能
  • 可以模仿动态类型使用 dynamic

除了用于移动和网络开发的使用外,扑波是开发套件 紫红色是谷歌开发的实验操作系统。

本教程将向您介绍Dart基础知识,如:

  • 变量,数据类型和运算符
  • 条件和循环
  • 功能,匿名功能和封闭
  • 箭头函数语法

您可以超越基础知识,并在我们的课程中了解达特方面的面向对象编程以及Dart Collection类型,如我们课程中的列表,集和地图 镖 - 基础上的编程,此简短教程是基于的。

完成教程后,您应该准备好使用DART潜入颤动开发。你可以开始扑腾 这里.

入门

要快速起飞以获得学习飞镖,最好选择使用 镖pad. 编辑,发现 //dartpad.dartlang.org:

镖pad.

镖pad是一个像典型IDE一样设置的。有:

  • 一个 编辑窗格 on the left
  • A 按钮在编辑器中运行代码
  • A 安慰 在右上方显示输出
  • 一个 信息 右下角的面板显示信息突出显示的代码
  • A 样本 下拉显示一些示例代码
  • A 分享 按钮您可以用来分享您创建的Dartpad文件

在下右下方右下方,有一个复选框来展示与使用DART进行Web编程的多个相关的面板,以及一些文本,显示Dartpad中使用的DART的当前版本。

如果您愿意,您可以在机器上本地安装DART SDK。这样做的一种方法是 安装Flutter SDK。安装颤动还将安装DART SDK。

您也可以通过访问直接安装DART SDK 这里.

核心概念

镖程序从呼叫到“Main`”功能,以及`Main`的语法看起来与其他语言的语法非常相似,如C,SWIFT或Kotlin等其他语言。

清除默认Dartpad中的所有代码,并向编辑器添加一个`main`函数:

void main() {
}

The main function is preceded by a return type, which in Dart is void, meaning nothing is returned. The parentheses after main indicate that this is a function definition, and the curly braces contain the body of the function. Inside main, you add the Dart code for your program.

变量,评论和数据类型

The first thing we’ll add to main is a variable assignment statement. 变量 hold the data that your program will work on. You can think of a variable like a box in your computer’s memory that holds a value. Each box has a name, the name for the variable. You use the var keyword in Dart to denote a variable.

Add a new variable to main:

var myAge = 35;  

Like C and Java, each Dart statement ends in a semicolon. You’ve created a myAge variable set it equal to 35.

You can use the built-in print function in Dart to print the variable to the console, so add that call after the variable:

print(myAge); // 35

点击 DartPad中的按钮运行代码,您将看到右上角的控制台中打印出的变量。

DART中的评论看起来像C的其他语言的那些:文字 // 在一行或文本内 / * ... * / blocks.

// This is a comment.
print(myAge); // This is also a comment.

/*
 And so is this.
 */

If you put the cursor in the editor over the myAge name, you’ll see in the lower right panel that Dart has 推断 that myAge is an int variable, thanks to being initialized with the integer value 35. Like Swift and Kotlin, Dart uses 类型推断 如果没有直接指定它,请尝试弄清楚日期的类型。

类型推断

一个 alternative to using type inference is to replace the var keyword with the specific type you want to use:

int yourAge = 27;
print(yourAge); // 27

类似于许多语言,如C,Java,Swift和Kotlin,Dart是 静态打字。这意味着Dart中的每个变量都有一种类型,必须在编译代码时知道,并且在运行程序时,变量的类型无法更改。

这与Python和JavaScript这样的语言形成对比 动态类型,含义变量可以在运行时保持不同类型的数据,并且在编译代码时不需要知道该类型。

基本飞镖类型

镖 uses int 为了 integers, double 为了 floating points, and bool 为了 booleans. ints and doubles are both derived from a type named num. You use the String type to represent sequences of characters. Dart also has a keyword dynamic which lets you mimic dynamic typing in the statically typed Dart.

DART数据类型

You can also use type inference for types other than int. Enter a variable pi equal to 3.14 like so:

var pi = 3.14;
print(pi); // 3.14

pi is inferred to be a double since you used a floating-point value to initialize it. You can see that in the Dart info panel

You can also just use double as the type instead of var:

double c = 299792458;
print(c); // 299792458

In this case, you’ve initialized c, the symbol for the speed of light, with an int, but because you specified the type as double, c is in fact a double. Dart will convert the int to a double in order to initialize c. So unlike Swift, Dart has 隐式类型转换.

动态关键字

If you use the dynamic keyword instead of var, you get what is effectively a dynamically-typed variable:

dynamic numberOfKittens;

You can set numberOfKittens to a String using quotes (see below for more on the String type)

numberOfKittens = 'There are no kittens!';
print(numberOfKittens); // There are no kittens!

numberOfKittens has a type, as it must since Dart has static typing. But that type is dynamic, which means you can assign other values with other types to it. So you can assign an int value below your print statement.

numberOfKittens = 0;
print(numberOfKittens); // 0

或者如果你有一只小猫 Schrödinger的盒子, you could assign a double value:

numberOfKittens = 0.5;
print(numberOfKittens); // 0.5

Schrödingers猫

继续点击 to see the three different values for numberOfKittens all printed out in the console. In each case, the type of numberOfKittens remains dynamic, even though the variable itself holds values of different types.

BOOL类型用于保持TRUE或FALSE的值。

bool areThereKittens = false;
print(areThereKittens); // false

但是,如果你在Schrödinger盒里面看,你可以切换到有一个真正的直播小猫:

numberOfKittens = 1;
areThereKittens = true;
print(areThereKittens); // true

再次运行代码以查看控制台中的布尔值。这是你看着盒子的好事! :]

运营商

镖拥有来自其他语言的所有常用运营商,如C,SWIFT和Kotlin。

算术 运营商, 平等, 增量递减, 比较, 和 逻辑 operators.

飞镖还允许 操作员重载 像C ++和Kotlin一样,但这超出了本教程的范围。

算术运营商工作只是喜欢你期待的。为您的Dartpad添加一堆操作:

print(40 + 2); // 42
print(44 - 2); // 42
print(21 * 2); // 42
print(84 / 2); // 42

在这里查看更多 42.

回答生活宇宙和一切

您可以使用算术表达式初始化变量:

var atltuae = 84.0 / 2;
print(atltuae); // 42

镖 converts the int to a double prior to the operation, so that the resulting variable is inferred to be a double.

DART有双重平等和不等于运营商:

print(42 == 43); // false
print(42 != 43); // true

有预先和修复后的增量和递减运算符:

print(atltuae++); // 42
print(--atltuae); // 42

因为增量的使用是Postfix,所以在递增之前打印42。减量是前缀,因此43递减为42,然后打印值42。

DART具有典型的比较运算符,如小于或大于或等于。

print(42 < 43); // true
print(42 >= 43); // false

还有通常的复合算术/分配运营商

atltuae += 1; print(atltuae); // 43
atltuae -= 1; print(atltuae); // 42
atltuae *= 2; print(atltuae); // 84
atltuae /= 2; print(atltuae); // 42

而Dart有通常的模算符。

print(392 % 50); // 42

The logical operators such as && 为了 || 为了 或者 看起来就像那些来自其他语言的那些。

print((41 < atltuae) && (atltuae < 43)); // true
print((41 < atltuae) || (atltuae > 43)); // true

并且否定运算符是感叹号,将虚假变为真实,真实为false。

print(!(41 < atltuae)); // false

The Dart string type is String. Strings are expressed in Dart using text surrounded by 任何一个 单引号或双引号。

Like for the other types we've seen, you can use either var 和 type inference or String to create a string variable:

var firstName = 'Albert';
String lastName = "Einstein";

与Kotlin和Swift这样的语言类似,您可以在字符串内部嵌入值和表达式以创建新字符串,使用美元符号符号 $.

var physicist = "$firstName $lastName";
print(physicist); // Albert Einstein

您可以组合相邻字符串,例如,长条带,即多行,只需将彼此旁边或单独的线路放在旁边:

var quote = 'If you can\'t' ' explain it simply\n'
  "you don't understand it well enough.";
print(quote);
// If you can't explain it simply
// you don't understand it well enough.

Here in the first string, you used single quotes and so used an escape sequence \' to embed a quotation mark for 不能 into the string. The escape sequences used in Dart are similar to those used in other C-like languages, for example, \n 为了 a newline.

Since you used double-quotes to delimit the second string, you did not need an escape sequence for the single quote on don't.

您还可以使用使用的字符串 + operator:

var energy = "Mass" + " times " + "c squared";
print(energy); // Mass times c squared

您可以使用三重引号来拥有一个字符串运行多行并保存格式:

var model = """
I'm not creating the universe.
I'm creating a model of the universe,
which may or may not be true.""";
print(model);
// I'm not creating the universe.
// I'm creating a model of the universe,
// which may or may not be true.

如果您需要在字符串中显示的转义序列,则可以使用 原始字符串,它是由r前缀的。

var rawString = r"If you can't explain it simply\nyou don't understand it well enough.";
print(rawString); 
// If you can't explain it simply\nyou don't understand it well enough.

继续点击 在Dartpad中,查看控制台中的所有字符串。

不可变形

镖 has the keywords constfinal 为了 values that don't change. const is used for values that are known at compile-time, final is used for values that don't have to be known at compile-time but cannot be re-assigned after being initialized. final acts like val in Kotlin or let in Swift.

You can use constfinal in place of var 和 let type inference determine the type:

const speedOfLight = 299792458;
print(speedOfLight); // 299792458

So speedOfLight is inferred to be an int, 一种s you can see in the info panel of DartPad.

final 方法 不可变, 和 final values cannot be re-assigned. You can also explicitly state the type with either final 或者 const:

final planet = 'Jupiter';
// final planet = 'Mar'; // error: planet is immutable
final String moon = 'Europa';
print('$planet has a moon $moon');
// Jupiter has a moon Europa

无效

For any variable, no matter the type, if you do not initialize the variable, the variable will be given the value null, which means 没有 存储在变量中。

这与像Swift和Kotlin这样的语言相反,你必须 明确 将变量声明为可用的(aka 选修的 在Swift)。这些语言中的默认类型是非可用的。

It turns out that all Dart types, even basic types like intdouble, 一种re derived from a type named Object. And if you don't initialize an object, it takes on a null value.

您将在此处在驾驶中安全地处理空值的某些方法,但它不会在Kotlin中的SWIFT或无无所作为中选择。

创建三种不同类型的变量,然后立即打印它们。

int age;
double height;
String err;
print(age); // null
print(height); // null
print(err); // null

You'll see that each of the variables is null in the console.

飞镖有一些 无效 操作符您可以使用以使用空值。

The double-question mark operator ?? is like the "Elvis operator" in Kotlin: it will return the left-hand operand if it's not-null, otherwise the right-hand value:

var error = err ?? "No error";
print(error); // No error

There's a corresponding assignment operator ??= that does similar:

err ??= error;
print(err); // No error

Since you just made error non-null with a value "No error", the err value now picks up that non-null value on this assignment.

There's also an operator ?. that protects you from accessing properties on null objects. It will return null if the object itself is null. Otherwise, it returns the value of the property on the right-hand side:

print(age?.isEven); // null

If you tried just age.isEvenage was null, you'd get an 未捕获的异常.

控制流

控制流程让您指示执行某些代码行,跳过或重复。控制流程在DART中处理 条件循环.

条件

The most basic form of control flow is deciding whether to execute or skip over certain parts of your code, depending on conditions that occur as your program runs. The language construct for handling conditions is the if/else statement. if/else in Dart looks nearly identical to the use in other C-like languages.

假设您有一个目前是狐狸的动物变量。

var animal = 'fox';

狐狸

You can use an if statement to check whether the animal is a cat or dog, and run some corresponding code if so.

if (animal == 'cat' || animal == 'dog') {
  print('Animal is a house pet.');
}

Here you've used the equality and or operators to create a bool value inside the condition for the if statement.

You can use an else clause to run alternative code if the condition is false:

} else {
  print('Animal is NOT a house pet.');
}
// Animal is NOT a house pet.

You can also combine multiple if/else statements into an if/else if/else construct:

if (animal == 'cat' || animal == 'dog') {
  print('Animal is a house pet.');
} else if (animal == 'rhino') {
  print('That\'s a big animal.');
} else {
  print('Animal is NOT a house pet.');
}
// Animal is NOT a house pet.

You can have as many else if branches in between ifelse as needed.

徘徊

循环允许您重复一定次数或基于某些条件重复代码。后者是由处理的 徘徊.

有 two forms of while loop in Dart, whiledo-while. The difference is that for while, the loop condition is before the code block, and in do-while the condition is after. So for do-while, the code block is guaranteed to run at least one time.

Create a variable i initialized to 1:

var i = 1;

You can use a while loop to print i while incrementing it, and set the condition to be that i is less than 10:

while (i < 10) {
  print(i);
  i++;
}
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9

跑 the code and you see the numbers 1 to 9 printed out by the while loop.

Reset i in DartPad and then add a do-while loop:

i = 1;
do {
  print(i);
  ++i;
} while (i < 10);
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9

这里的结果与之前的结果相同,就在此时,在检查循环退出条件之前,循环体运行一次。

继续和休息

镖 has the usual continuebreak keywords for use in loops and elsewhere. continue will skip remaining code inside a loop and immediately go to the next iteration. break stops the loop and continues execution after the body of the loop.

You must be careful when using continue in your code. For example, if you take the do-while loop from above, and say you want to continue when i is equal to 5, that could result in an 无限循环 that just keeps running, depending in where you place the continue statement:

do {
  print(i);
  if (i == 5) {
    continue;
  }            
  ++i;
} while (i < 10);
// 1
// 2
// 3
// 4
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// ...

The infinite loop occurs since once i is 5, you never increment i, 和 the condition always stays true.

If you run this in DartPad, the infinite loop will cause the browser to hang. Instead use break, so that the loop will end after i reaches 5:

do {
  print(i);
  if (i == 5) {
    break;
  }
  ++i;
} while (i < 10);
// 1
// 2
// 3
// 4
// 5

立即运行代码,并在5次迭代后,循环结束。

对于循环

循环循环预定次数是 为了 Dart中的循环,再次与其他语言的循环非常相似。

镖具有f用于循环的C形式,具有初始化,循环条件和操作,以及用于迭代对象的集合。在第一种形式中,初始化在第一个循环迭代之前运行。在输入每个迭代时检查条件,并在开始下一次迭代之前运行该操作。

对于for-in表单,将变量设置为循环的每个后续迭代的DART对象集中的每个元素。假设您希望总结前10个整数的值。

为总和创建一个变量:

var sum = 0;

Then use a for loop in which you initialize a loop counter i to 1, check that i is less than or equal to 10, and increment i after every loop. Inside the loop use a compound assignment to add i to the running sum:

为了 (var i = 1; i <= 10; i++) {
  sum += i;  
}
print("The sum is $sum"); // The sum is 55

在Dartpad中运行代码以查看总和。

DART系列的示例是使用方括号制作的简单数字列表:

var numbers = [1, 2, 3, 4];

您可以使用for-in循环来迭代列表:

为了 (var number in numbers) {
  print(number);
}
// 1
// 2
// 3
// 4

The variable number takes on the value of each element of numbers as you iterate in the loop.

Lists like numbers also have a function you can call on them named 为了Each, which simplifies the previous loop down to one line:

numbers.forEach((number) => print(number));
// 1
// 2
// 3
// 4

在这里你用过了 匿名功能箭头语法,两者都在稍后在部分内看到 功能.

Finally, like while loops, for loops can also use continuebreak to control flow within the loop. For example, if you want to skip printing the number 3, you can use a continue statement in the 为了-in loop:

for (var number in numbers) {
  if (number == 3) {
    continue;
  }
  print(number);
}
// 1
// 2
// 4

开关和枚举

镖 also has support for a switch statement and enumerations using enum. Consult the 飞镖文件 有关两者的更多。像你所看到的大多数镖构建体一样,它们类似地与他们如何以其他语言工作,如C和Java。

功能

函数让您将多行相关的代码打包到一个身体中,以召唤以避免在整个Dart应用程序中重复这些代码行:

功能

函数由一个函数组成 返回类型, 一种 函数名称, 一种 参数列表 在括号中,然后是一个 功能机身 括在括号中。您正在进行进入函数的代码会在括号内。当您调用函数时,您将通过 争论 匹配函数参数的类型。

笔记: Specifying a return type on functions is optional. If you leave off the return type, values returned from the function will either have an inferred type, or be dynamic if the type cannot be inferred. That allows you to return values of different types from the function. Usually you'll want to avoid this and instead specify a single return type from functions.

Typically, functions are defined either outside other functions or inside Dart classes, but you can also nest Dart functions in one another. For example, you can add the functions in this section inside main.

在Dartpad中写一个新功能,只需检查给定的字符串是香蕉。

bool isBanana(String fruit) {
  return fruit == 'banana';
}

The function uses return to return a bool value determined by the argument passed to the function. This function will always return the same value for any given input. If a function does not need to return a value, you can set the return type to void, such as for the main function.

You can call the function by passing in a string. Then you might pass the result of that call onto print:

var fruit = 'apple';
print(isBanana(fruit)); // false

您可以将传递给函数的参数更改,并再次使用新参数调用它们:

fruit = 'banana';
print(isBanana(fruit));  // true

调用函数的结果完全取决于传入的参数。

可选参数

如果函数的参数是可选的,则可以使用方括号括起来:

String fullName(String first, String last, [String title]) {
  return "${title== null ? "" : "$title "}$first $last";
}

If an optional parameter is not included in the function call, the value used is null 为了 the parameter inside the function body.

然后,您可以使用可选参数调用函数:

print(fullName("Joe", "Howard"));
// Joe Howard

print(fullName("Albert", "Einstein", "Professor"));
// Professor Albert Einstein

可选命名参数

使用Dart功能,您可以使用 可选命名参数 通过括号的参数列表:

bool withinTolerance({int value, int min, int max}) {
  return min <= value && value <= max;
}

然后,您可以通过使用冒号提供参数名称来以不同的顺序传递参数:

print(withinTolerance(min: 1, max: 10, value: 11)); // false

类似于可选参数,不需要将具有可选名称的参数添加到函数调用中,并且将给出相应的参数值 null in the function.

默认值

您也可以分配 默认值 使用等式的一个或多个参数:

bool withinTolerance({int value, int min = 0, int max = 10}) {
  return min <= value && value <= max;
}

然后,您可以在调用函数时留下默认值的参数。

print(withinTolerance(value: 5)); // true

运行代码以查看您的新功能。

一流的功能

镖支持所谓的内容 一流的功能。该术语意味着函数被视为任何其他数据类型,即,它们可以被分配给变量,传递为参数,并从其他函数返回。

You can use the Function type to specify that a parameter named op is a function itself:

int applyTo(int value, int Function(int) op) {
  return op(value);
}

So if you have a function named square:

int square(int n) {
  return n * n;
}

You can pass square to applyTo as an argument:

print(applyTo(3, square)); // 9

您可以将函数分配给变量:

var op = square;

然后,您可以调用变量上的函数,就像它是原始函数的别名一样:

print(op(5)); // 25

您将在稍后一点地看到有关从其他功能中返回函数的更多信息。

匿名功能和闭包

到目前为止你见过的功能 姓名d functions,函数名称。 匿名功能 只是你可能期望的,没有名字的职能。您还可以删除将被推断的返回类型。因此,您只需要一个参数列表和函数正文,以获得匿名函数。

您可以为变量分配匿名函数:

var multiply = (int a, int b) {
  return a * b;
};

右侧由参数列表和函数正文组成。

Since multiply now holds an anonymous function, you can call it as you would any other function:

print(multiply(14, 3)); // 42

You've seen a preview earlier of lists and the 为了Each function. 为了Each is a great example of using an anonymous function.

因此,如果您有数字列表:

numbers = [1, 2, 3];

You can call 为了Each on the list and pass in an anonymous function that triples an element and prints out the tripled value:

numbers.forEach((number) { 
  var tripled = number * 3;  
  print(tripled);
  // 3
  // 6
  // 9
});

您可以从另一个功能返回匿名功能:

Function applyMultiplier(num multiplier) {
  return (num value) { 
    return value * multiplier;    
  };
}

This is useful for generating functions with a given behavior but with varying input parameter values. So the return value here is a function that takes one num parameter and multiplies it by the multiple used to generate the function.

一个例子是创建一个名为triple的变量,该变量将其输入乘以3:

var triple = applyMultiplier(3);

您可以使用任一类型的NUM调用三倍:

print(triple(6)); // 18
print(triple(14.0)); // 42

DART中的匿名功能充当 关闭, which means they "close-over" variables defined outside of themselves. For example, the return value of the applyMultiplier function above is a closure that has access to the multiplier variable defined elsewhere, in that case in the parameter list for applyMultiplier itself.

箭头语法

当一个掷骰子函数,任一个名为或匿名,只包含一行代码,可以使用DART减少函数正文 箭头语法.

For example, multiply above becomes:

var multiply = (int a, int b) => a * b;

You've removed the braces and the return statement.

You can also use arrow syntax with applyMultiplier:

Function applyMultiplier(num multiplier) =>
  (num value) => value * multiplier;

You've used arrow syntax twice here: the first is denoting the return value for the applyMultiplier function, the second is within the return value itself, which is an anonymous function.

In the example just above using 为了Each, you cannot use arrow syntax, since the body of the function you're passing to 为了Each has more than one line of code.

然后去哪儿?

结束了这段简介驾驶基础知识。您现在应该更好地了解您在学习如何构建浮动应用程序时看到的飞镖代码。

单击,您可以下载本教程的所有代码 下载材料 页面顶部或底部的按钮。您可以粘贴代码 main.dart. 文件进入DartPad或使用DART SDK运行该文件。

如引言中所述,您可以超越基础知识并了解更多信息 面向对象的编程 在飞镖和飞镖 收集类型 如列表,集和地图,我们的课程 镖 - 基础上的编程,此简短教程是基于的。

看看 官方飞镖文件 了解Dart的中间和高级部分:

  • 迭代和发电机
  • 例外
  • 符号和符号
  • Asynchronous Dart with isolates, streams, futures and async/await

我们将在未来的教程和视频课程中涵盖这些和其他DART主题。

我希望您喜欢这篇简短的飞镖基础知识。如果您有疑问或意见,请在下面的论坛中写信给我们!

平均评级

4.7/5

为此内容添加评级

40 ratings

更像这样的

贡献者

评论