Flutter学习笔记2-Dart基础

变量

var name = 'Bob';
dynamic name = 'Bob';
String name = 'Bob';
final name = 'Bob'; // A final variable can be set only once
final String nickname = 'Bobby';
const bar = 1000000; // compile-time constants
const double atm = 1.01325 * bar; 

Number

int x = 1;
int hex = 0xDEADBEEF;
var one = int.parse('1');//1
var onePointOne = double.parse('1.1');//1.1
String oneAsString = 1.toString();//'1'
String piAsString = 3.14159.toStringAsFixed(2);//'3.14'

String

var s2 = 'The + operator ' + 'works, as well.';
var content = 'world';
var hello = 'Hello ${content}';//Hello world

List

var list = [1, 2, 3];
list.length == 3;
list[1] = 1;
var names = List();
names.addAll(['Seth', 'Kathy', 'Lars']);
names.add('Jack'); 

var constantList = const [1, 2, 3];
// constantList[1] = 1; // Uncommenting this causes an error.

var teas = ['green', 'black', 'chamomile', 'earl grey'];
teas.forEach((tea) => print('I drink $tea'));
var loudTeas =
    teas.map((tea) => tea.toUpperCase()).toList();

// Chamomile is not caffeinated.
bool isDecaffeinated(String teaName) =>
    teaName == 'chamomile';
// Use where() to find only the items that return true
// from the provided function.
var decaffeinatedTeas =
    teas.where((tea) => isDecaffeinated(tea));
// or teas.where(isDecaffeinated)
// Use any() to check whether at least one item in the
// collection satisfies a condition.
assert(teas.any(isDecaffeinated));
// Use every() to check whether all the items in a
// collection satisfy a condition.
assert(!teas.every(isDecaffeinated));

Map

var gifts = {
  // Key:    Value
  'first': 'partridge',
  'second': 'turtledoves',
  'fifth': 'golden rings'
};

var nobleGases = {
  2: 'helium',
  10: 'neon',
  18: 'argon',
};

var gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';

var nobleGases = Map();
nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';

var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds'; // Add a key-value pair

gifts.length == 2;//length

final constantMap = const {
  2: 'helium',
  10: 'neon',
  18: 'argon',
};
// constantMap[2] = 'Helium'; // Uncommenting this causes an error.


var nobleGases = {54: 'xenon'};
// Retrieve a value with a key.
assert(nobleGases[54] == 'xenon');
// Check whether a map contains a key.
assert(nobleGases.containsKey(54));
// Remove a key and its value.
nobleGases.remove(54);
assert(!nobleGases.containsKey(54));


var hawaiianBeaches = {
  'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
  'Big Island': ['Wailea Bay', 'Pololu Beach'],
  'Kauai': ['Hanalei', 'Poipu']
};
// Get all the keys as an unordered collection
// (an Iterable).
var keys = hawaiianBeaches.keys;
assert(keys.length == 3);
assert(Set.from(keys).contains('Oahu'));
// Get all the values as an unordered collection
// (an Iterable of Lists).
var values = hawaiianBeaches.values;
assert(values.length == 3);
assert(values.any((v) => v.contains('Waikiki')));
assert(hawaiianBeaches.containsKey('Oahu'));
hawaiianBeaches.forEach((k, v) {
  print('I want to visit $k and swim at $v');
  // I want to visit Oahu and swim at
  // [Waikiki, Kailua, Waimanalo], etc.
});

函数

bool isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

isNoble(atomicNumber) {//省略返回值声明
  return _nobleGases[atomicNumber] != null;
}

bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;//短语法

void enableFlags({bool bold = false, bool hidden = false}) {...}

([[Type] param1[, …]]) { //匿名函数
  codeBlock; 
}; 

类型测试

if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}

(emp as Person).firstName = 'Bob';//类型转换,但如果emp不是Person类型就会抛出异常

瀑布语法

querySelector('#confirm') // Get an object.
  ..text = 'Confirm' // Use its members.
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'));
//相当于
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));

控制语句

var callbacks = [];
for (var i = 0; i < 2; i++) {
  callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());

var collection = [0, 1, 2];
for (var x in collection) {
  print(x); // 0 1 2
}



遍历

class Process {
  // Represents a process...
}

class ProcessIterator implements Iterator {
  @override
  Process get current => ...
  @override
  bool moveNext() => ...
}

// A mythical class that lets you iterate through all
// processes. Extends a subclass of [Iterable].
class Processes extends IterableBase {
  @override
  final Iterator iterator = ProcessIterator();
}

void main() {
  // Iterable objects can be used with for-in.
  for (var process in Processes()) {
    // Do something with the process.
  }
}

异常

assert(number < 100);//Make sure the value is less than 100

//定义异常:
class FooException implements Exception {
  final String msg;

  const FooException([this.msg]);

  @override
  String toString() => msg ?? 'FooException';
}

throw FormatException('Expected at least 1 section');
try {
  breedMoreLlamas();
} on OutOfLlamasException {
  buyMoreLlamas();
}

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
}

try {
  breedMoreLlamas();
} catch (e) {
  print('Error: $e'); // Handle the exception first.
} finally {
  cleanLlamaStalls(); // Then clean up.
}

URI

var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeComponent(uri);//'http%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message'
var decoded = Uri.decodeComponent(encoded);

var uri =
    Uri.parse('http://example.org:8080/foo/bar#frag');
assert(uri.scheme == 'http');
assert(uri.host == 'example.org');
assert(uri.path == '/foo/bar');
assert(uri.fragment == 'frag');
assert(uri.origin == 'http://example.org:8080');

ar uri = Uri(
    scheme: 'http',
    host: 'example.org',
    path: '/foo/bar',
    fragment: 'frag');
assert(
    uri.toString() == 'http://example.org/foo/bar#frag');

abstract class Point {
  num x=4;
  num y;
  Point(this.x,this.y);
  Point.zero(){
    x= 0;
    y = 0;
  }
  void toStr();
}

class Dot extends Point {
  num radius;
  static const initialCapacity = 16;//类属性
  Dot.zero() : super.zero() {
      radius = 5;
  }

  num get left => x - radius;
  set centerX(num value) => x = value;

  void toStr(){
    print('(${x},${y},${radius})');
  }

  static printClassProp(){
    print('static $initialCapacity');
  }
}

枚举

enum Color { red, green, blue }
var aColor = Color.blue;

范型

abstract class Cache {
  T getByKey(String key);
  void setByKey(String key, T value);
}

var names = ['Seth', 'Kathy', 'Lars'];

class Foo {
  // Implementation goes here...
  String toString() => "Instance of 'Foo<$T>'";
}

var someBaseClassFoo = Foo();
class Extender extends SomeBaseClass {...}
var extenderFoo = Foo();
var foo = Foo();


T first(List ts) {
  // Do some initial work or error checking, then...
  T tmp = ts[0];
  // Do some additional checking or processing...
  return tmp;
}

引用库

import 'dart:html';
//The package: scheme specifies libraries provided by a package manager such as the pub tool
import 'package:test/test.dart';

import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;
// Uses Element from lib1.
Element element1 = Element();
// Uses Element from lib2.
lib2.Element element2 = lib2.Element();

// Import only foo.
import 'package:lib1/lib1.dart' show foo;
// Import all names EXCEPT foo.
import 'package:lib2/lib2.dart' hide foo;


import 'package:greetings/hello.dart' deferred as hello;//懒加载式声明
Future greet() async {
  await hello.loadLibrary();//加载库
  hello.printGreeting();//调用库
}

异步处理

Future checkVersion() async {
  var version = await lookUpVersion();
  // Do something with version
}

Future lookUpVersion() async => '1.0.0';//Declaring async functions

typedef

typedef Compare = int Function(Object a, Object b);

日期时间

DateTime.now()//当前时间
var y2k = DateTime(2000); // January 1, 2000

// Specify the month and day.
y2k = DateTime(2000, 1, 2); // January 2, 2000
// Specify the date as a UTC time.
y2k = DateTime.utc(2000); // 1/1/2000, UTC
// Specify a date and time in ms since the Unix epoch.
y2k = DateTime.fromMillisecondsSinceEpoch(946684800000,
    isUtc: true);
// Parse an ISO 8601 date.
y2k = DateTime.parse('2000-01-01T00:00:00Z');

var y2001 = y2k.add(const Duration(days: 366));
assert(y2001.year == 2001);

var duration = y2001.difference(y2k);
assert(duration.inDays == 366); // y2k was a leap year.

定时器

import 'dart:async';
Timer timer = new Timer(Duration(milliseconds: 100), update);
void update() {
    print('update');
    timer = new Timer(Duration(milliseconds: 100), update);
}

你可能感兴趣的:(Flutter学习笔记2-Dart基础)