Hello World

Every app has a main() function. To display text on the console, you can use the top-level print() function:

void main() {
print('Hello, World!');
}

Variables

Even in type-safe Dart code, most variables don’t need explicit types, thanks to type inference:

var name = 'Voyager I';
var year = ;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
'tags': ['saturn'],
'url': '//path/to/saturn.jpg'
};

Read more about variables in Dart, including default values, the final and const keywords, and static types.

Control flow statements

Dart supports the usual control flow statements:

if (year >= ) {
print('21st century');
} else if (year >= ) {
print('20th century');
} for (var object in flybyObjects) {
print(object);
} for (int month = ; month <= ; month++) {
print(month);
} while (year < ) {
year += ;
}

Read more about control flow statements in Dart, including break and continueswitch and case, and assert.

Functions

We recommend specifying the types of each function’s arguments and return value:

int fibonacci(int n) {
if (n == || n == ) return n;
return fibonacci(n - ) + fibonacci(n - );
} var result = fibonacci();

A shorthand => (arrow) syntax is handy for functions that contain a single statement. This syntax is especially useful when passing anonymous functions as arguments:

flybyObjects.where((name) => name.contains('turn')).forEach(print);

Besides showing an anonymous function (the argument to where()), this code shows that you can use a function as an argument: the top-level print() function is an argument to forEach().

Read more about functions in Dart, including optional parameters, default parameter values, and lexical scope.

Comments

Dart comments usually start with //.

// This is a normal, one-line comment.

/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially. /* Comments like these are also supported. */

Read more about comments in Dart, including how the documentation tooling works.

Imports

To access APIs defined in other libraries, use import.

// Importing core libraries
import 'dart:math'; // Importing libraries from external packages
import 'package:test/test.dart'; // Importing files
import 'path/to/my_other_file.dart';

Read more about libraries and visibility in Dart, including library prefixes, show and hide, and lazy loading through the deferred keyword.

Classes

Here’s an example of a class with three properties, two constructors, and a method. One of the properties can’t be set directly, so it’s defined using a getter method (instead of a variable).

class Spacecraft {
String name;
DateTime launchDate; // Constructor, with syntactic sugar for assignment to members.
Spacecraft(this.name, this.launchDate) {
// Initialization code goes here.
} // Named constructor that forwards to the default one.
Spacecraft.unlaunched(String name) : this(name, null); int get launchYear =>
launchDate?.year; // read-only non-final property // Method.
void describe() {
print('Spacecraft: $name');
if (launchDate != null) {
int years =
DateTime.now().difference(launchDate).inDays ~/
365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}

You might use the Spacecraft class like this:

var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
voyager.describe(); var voyager3 = Spacecraft.unlaunched('Voyager III');
voyager3.describe();

Read more about classes in Dart, including initializer lists, optional new and const, redirecting constructors, factory constructors, getters, setters, and much more.

Inheritance

Dart has single inheritance.

class Orbiter extends Spacecraft {
num altitude;
Orbiter(String name, DateTime launchDate, this.altitude)
: super(name, launchDate);
}

Read more about extending classes, the optional @override annotation, and more.

Mixins

Mixins are a way of reusing code in multiple class hierarchies. The following class can act as a mixin:

class Piloted {
int astronauts = 1;
void describeCrew() {
print('Number of astronauts: $astronauts');
}
}

To add a mixin’s capabilities to a class, just extend the class with the mixin.

class PilotedCraft extends Spacecraft with Piloted {
// ···
}

PilotedCraft now has the astronauts field as well as the describeCrew() method.

Read more about mixins.

Interfaces and abstract classes

Dart has no interface keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.

class MockSpaceship implements Spacecraft {
// ···
}

Read more about implicit interfaces.

You can create an abstract class to be extended (or implemented) by a concrete class. Abstract classes can contain abstract methods (with empty bodies).

abstract class Describable {
void describe(); void describeWithEmphasis() {
print('=========');
describe();
print('=========');
}
}

Any class extending Describable has the describeWithEmphasis() method, which calls the extender’s implementation of describe().

Read more about abstract classes and methods.

Async

Avoid callback hell and make your code much more readable by using async and await.

const oneSecond = Duration(seconds: );
// ···
Future<void> printWithDelay(String message) async {
await Future.delayed(oneSecond);
print(message);
}
The method above is equivalent to: Future<void> printWithDelay(String message) {
return Future.delayed(oneSecond).then((_) {
print(message);
});
}

As the next example shows, async and await help make asynchronous code easy to read.

Future<void> createDescriptions(Iterable<String> objects) async {
for (var object in objects) {
try {
var file = File('$object.txt');
if (await file.exists()) {
var modified = await file.lastModified();
print(
'File for $object already exists. It was modified on $modified.');
continue;
}
await file.create();
await file.writeAsString('Start describing $object in this file.');
} on IOException catch (e) {
print('Cannot create description for $object: $e');
}
}
}

You can also use async*, which gives you a nice, readable way to build streams.

Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
for (var object in objects) {
await Future.delayed(oneSecond);
yield '${craft.name} flies by $object';
}
}

Read more about asynchrony support, including async functions, FutureStream, and the asynchronous loop (await for).

Exceptions

To raise an exception, use throw:

if (astronauts == ) {
throw StateError('No astronauts.');
}

To catch an exception, use a try statement with on or catch (or both):

try {
for (var object in flybyObjects) {
var description = await File('$object.txt').readAsString();
print(description);
}
} on IOException catch (e) {
print('Could not describe object: $e');
} finally {
flybyObjects.clear();
}

Note that the code above is asynchronous; try works for both synchronous code and code in an async function.

Read more about exceptions, including stack traces, rethrow, and the difference between Error and Exception.

Dart Language samples的更多相关文章

  1. Dart 基础重点截取 Dart 2 20180417

    官网教程 https://www.dartlang.org/guides/language/language-tour dart是一个单线程的语言,没有多线程 Final and const If y ...

  2. dart之旅(一)

    前言 最近在看 dart 了,本着 "纸上得来终觉浅,绝知此事 markdown" 的原则,准备边学边写,写一个系列,这是第一篇.学习过程中主要是参考 A Tour of the ...

  3. Dart语法学习

    Dart语法学习 目录 参考资料 语言特性 关键字 变量与常量 数据类型 运算符 operators 控制流程语句 异常 Exceptions 函数 Function 类 Class 类-方法 类-抽 ...

  4. Flutter学习笔记(6)--Dart流程控制语句

    如需转载,请注明出处:Flutter学习笔记(5)--Dart流程控制语句 条件语句:if.if...elseif.if...elseif...else ; ) { print('优秀'); } &g ...

  5. Dart语言学习(十) Dart流程控制语句

    一.条件语句:if.if...elseif.if...elseif...else int score = 95; if (score >=90) { print('优秀'); } else if ...

  6. Dart Memo for Android Developers

    Dart Memo for Android Developers Dart语言一些语法特点和编程规范. 本文适合: 日常使用Kotlin, 突然想写个Flutter程序的Android程序员. Dar ...

  7. Dart 学习

    语言特性 Dart所有的东西都是对象, 即使是数字numbers.函数function.null也都是对象,所有的对象都继承自Object类. Dart动态类型语言, 尽量给变量定义一个类型,会更安全 ...

  8. Cheatsheet: 2013 09.10 ~ 09.21

    .NET Lucene.Net – Custom Synonym Analyzer Using FiddlerCore to Capture Streaming Audio Immutable col ...

  9. linq字符串搜索条件,排序条件-linq动态查询语句 Dynamic LINQ

    在做搜索和排序的时候,往往是前台传过来的字符串做条件,参数的数量还不定,这就需要用拼sql语句一样拼linq语句.而linq语句又是强类型的,不能用字符串拼出来. 现在好了,有个开源的linq扩展方法 ...

随机推荐

  1. ggplot2绘制Excel所有图

    出处:https://brucezhaor.github.io/blog/2016/06/13/excel2ggplot/#%E5%89%8D%E8%A8%80 目录 前言 1.用到的包 2.数据准备 ...

  2. 7月新的开始 - Axure学习02 - 页面属性、钢笔工具

    页面属性 页面属性可以修改整个页面的效果 包含: 属性.对交互用力和事件的编辑 样式.对页面的样式操作 说明.可以对整个页面进行说明.以及样式的说明 钢笔工具:锚点.路径 锚点:钢笔点击之后的点就是锚 ...

  3. 如何比较js 浮点数

    浮点数的定义,非整数的Number类型无法用 ==(===也不行) 来比较,这就是为什么在JavaScript中,0.1+0.2不能=0.3: console.log( 0.1 + 0.2 == 0. ...

  4. mysql group_concat长度限制

    group_concat函数有长度限制 查找当前数据库长度 show variables like 'group_concat_max_len' 设置当前session的group_concat长度, ...

  5. 怎么学好js

    Js给人那种感觉的原因多半是因为它如下的特点: A:本身知识很抽象.晦涩难懂,如:闭包.内置对象.DOM. B:本身内容很多,如函数库.对象库就一大堆. C:混合多种编程思想.它里面不但牵涉面向过程编 ...

  6. JAVA类的无参方法

    Java注释:                //:单行注释                /**/:多行注释                /**    */:JavaDoc注释    方法:   ...

  7. react 后台(一) react + redux + react-route + webpack+ axios + antd + less

    create-react-app 项目名称(项目失败,ant 的样式出不来) 项目技术栈 react + redux + react-route + webpack+ axios + less + a ...

  8. CF D. Ehab and the Expected XOR Problem 贪心+位运算

    题中只有两个条件:任意区间异或值不等于0或m. 如果只考虑区间异或值不等于 0,则任意两个前缀异或值不能相等. 而除了不能相等之外,还需保证不能出现任意两个前缀异或值不等于m. 即 $xor[i]$^ ...

  9. Codeforces 1220 E Tourism

    题面 可以发现一个边双必然是可以随意走的,所以我们就把原图求割边然后把边双缩成一个点,然后就是一个树上dp了. #include<bits/stdc++.h> #define ll lon ...

  10. linux下设置git代理访问.

    有时候克隆仓库巨慢无比,需要设置代理. 一般情况下 proxychains 可以搞定的. 但是某些情况,如go 安装模块的时候是调用git的.这个时候proxchains就不行了. go 也可以通过设 ...