Dart基础使用手册

程序入口

在每个app中必须有一个main()函数作为程序的入口点。

你可以在新建的flutter项目中找到它(main.dart)

void main() => runApp(MyApp())

控制台输出

print('this is a log')

变量

Dart是类型安全的 变量必须是明确声明的或者是系统能够解析的类型

String name = 'hello';
var name = 'hello'
//两种都可以

在Dart中,未初始化的变量的初始值为null

布尔

在Dart中,只有布尔值为"true"才被认为true,0不算

null检查

  • ?.运算符左边为null的情况会直接走左边的调用,类似三目运算符
  • ??运算符为在左侧表达式为null时为其设置默认值

函数

add(){
    
}

String getAString(String output){
    return output;
}

注释

// 单行

///
/// 文档注释

/* */ 多行

引用

//引用核心库
import 'dart:async';
import 'dart:math';

//引用外来库
import 'package:angular2/angular2.dart';

//引用文件
import 'path/filename'

声明类

class Spacecraft {
  String name;
  DateTime launchDate;
  int launchYear;

  // 包含成员变量的构造器
  Spacecraft(this.name, this.launchDate) {
    launchYear = launchDate?.year;
  }

  // 命名构造函数
  Spacecraft.unlaunched(String name) : this(name, null);

  // 方法
  void describe() {
    print('Spacecraft: $name');
    if (launchDate != null) {
      int years = new DateTime.now().difference(launchDate).inDays ~/ 365;
      print('Launched: $launchYear ($years years ago)');
    } else {
      print('Unlaunched');
    }
  }
}

使用类

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

var voyager3 = new Spacecraft.unlaunched('Voyager III');
voyager3.describe();

继承

在Dart中也是使用extends来继承的,同时Dart是单继承

接口

Dart没有interface关键字。在 Dart 中所有的类都隐含的定义了一个接口。因此你可以使用 implement 来实现任意的类隐含定义的接口。

抽象类

abstract class Describable {
  void describe();

  void describeWithEmphasis() {
    print('=========');
    describe();
    print('=========');
  }
}

任何继承 Describable 的类都有一各 describeWithEmphasis() 函数,这个函数调用子类的 describe() 函数。

异步编程

Dart使用Future来表示
使用 asyncawait 可以避免回调接口嵌套的问题,让异步代码更加简洁。

Future<Null> printWithDelay(String message) async {
  await new Future.delayed(const Duration(seconds: 1));
  print(message);
}

错误异常

抛出异常

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

捕获异常

异常可以被捕捉,在异步中也可以

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

Getters 和 Setter

class Spacecraft {
  // ...
  DateTime launchDate;
  int get launchYear => launchDate?.year;
  // ...
}

猜你喜欢

转载自www.cnblogs.com/sixFlower/p/11121331.html
今日推荐