Instantly share code, notes, and snippets.

Embed
What would you like to do?
JW 课程 - Flutter 移动应用开发实战(https://blog.jaggerwang.net/jw-course-flutter-mobile-app-development/) - Dart 语言示例代码
void main() {
var name = 'Dart';
print('Hello $name');
}
void main() {
var name = 'Jagger Wang';
String nickname = '天火';
var n;
print(n);
final s = 'Jagger Wang';
const c = 'Jagger Wang';
// s = 'JW';
// c = 'JW';
const r = 10;
const double area = 3.1415926 * r * r;
var v1 = const [];
final v2 = const [];
const v3 = [];
v1 = [1, 2, 3];
// v2 = [42];
// v3 = [42];
}
void main() {
var x = 1;
var hex = 0xDEADBEEF;
var y = 1.1;
var exponents = 1.42e5;
double z = 1;
var one = int.parse('1');
assert(one == 1);
var onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);
String oneAsString = 1.toString();
assert(oneAsString == '1');
String piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == '3.14');
assert((3 << 1) == 6);
assert((3 >> 1) == 1);
assert((3 | 4) == 7);
const msPerSecond = 1000;
const secondsUntilRetry = 5;
const msUntilRetry = secondsUntilRetry * msPerSecond;
var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";
var s = 'string interpolation';
assert('Dart has $s, which is very handy.' ==
'Dart has string interpolation, ' + 'which is very handy.');
assert('That deserves all caps. ' + '${s.toUpperCase()} is very handy!' ==
'That deserves all caps. ' + 'STRING INTERPOLATION is very handy!');
s1 = 'String '
'concatenation'
" works even over line breaks.";
assert(s1 ==
'String concatenation works even over '
'line breaks.');
s2 = 'The + operator ' + 'works, as well.';
assert(s2 == 'The + operator works, as well.');
s1 = '''
You can create
multi-line strings like this one.
''';
s2 = """This is also a
multi-line string.""";
s = r'In a raw string, not even \n gets special treatment.';
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';
var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1, 2, 3];
const validConstString = '$aConstNum $aConstBool $aConstString';
// const invalidConstString = '$aNum $aBool $aString $aConstList';
var fullName = '';
assert(fullName.isEmpty);
var hitPoints = 0;
assert(hitPoints <= 0);
var unicorn;
assert(unicorn == null);
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);
var list = [1, 2, 3];
assert(list.length == 3);
assert(list[1] == 2);
list[1] = 1;
assert(list[1] == 1);
var constantList = const [1, 2, 3];
// constantList[1] = 1;
var gifts = {
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
var nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};
gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';
nobleGases = Map();
nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';
gifts['fourth'] = 'calling birds';
assert(gifts['first'] == 'partridge');
gifts = {'first': 'partridge'};
assert(gifts['fifth'] == null);
gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds';
assert(gifts.length == 2);
final constantMap = const {
2: 'helium',
10: 'neon',
18: 'argon',
};
// constantMap[2] = 'Helium';
var clapping = '\u{1f44f}';
print(clapping);
print(clapping.codeUnits);
print(clapping.runes.toList());
Runes input =
Runes('\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}');
print(String.fromCharCodes(input));
}
var _nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};
bool isNoble(int atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
isNobleDynamic(atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
bool isNobleArrow(int atomicNumber) => _nobleGases[atomicNumber] != null;
void enableFlags({bool bold, bool hidden}) {}
String say(String from, String msg, [String device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
void enableFlagsDefault({bool bold = false, bool hidden = false}) {}
String sayDefault(String from, String msg,
[String device = 'carrier pigeon', String mood]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
if (mood != null) {
result = '$result (in a $mood mood)';
}
return result;
}
void doStuff(
{List<int> list = const [1, 2, 3],
Map<String, String> gifts = const {
'first': 'paper',
'second': 'cotton',
'third': 'leather'
}}) {
print('list: $list');
print('gifts: $gifts');
}
void printElement(int element) {
print(element);
}
bool topLevel = true;
Function makeAdder(num addBy) {
return (num i) => addBy + i;
}
foo() {}
void main() {
enableFlags(bold: true, hidden: false);
assert(say('Bob', 'Howdy') == 'Bob says Howdy');
assert(say('Bob', 'Howdy', 'smoke signal') ==
'Bob says Howdy with a smoke signal');
enableFlagsDefault(bold: true);
assert(sayDefault('Bob', 'Howdy') == 'Bob says Howdy with a carrier pigeon');
var l1 = [1, 2, 3];
l1.forEach(printElement);
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
assert(loudify('hello') == '!!! HELLO !!!');
var l2 = ['apples', 'bananas', 'oranges'];
l2.forEach((item) {
print('${l2.indexOf(item)}: $item');
});
l2.forEach((item) => print('${l2.indexOf(item)}: $item'));
var insideMain = true;
void myFunction() {
var insideFunction = true;
void nestedFunction() {
var insideNestedFunction = true;
assert(topLevel);
assert(insideMain);
assert(insideFunction);
assert(insideNestedFunction);
}
}
var add2 = makeAdder(2);
var add4 = makeAdder(4);
assert(add2(3) == 5);
assert(add4(3) == 7);
assert(foo() == null);
}
void main() {
var a = 1;
var b = 2;
var c = true;
print(a++);
print(a + b);
print(a = b);
print(a == b);
print(c ? a : b);
assert(a is int);
var n = 4;
var d = 6;
var i = 2;
assert((n % i == 0) && (d % i == 0));
assert(n % i == 0 && d % i == 0);
assert(2 + 3 == 5);
assert(2 - 3 == -1);
assert(2 * 3 == 6);
assert(5 / 2 == 2.5);
assert(5 ~/ 2 == 2);
assert(5 % 2 == 1);
assert('5/2 = ${5 ~/ 2} r ${5 % 2}' == '5/2 = 2 r 1');
a = 0;
b = ++a;
assert(a == b);
a = 0;
b = a++;
assert(a != b);
a = 0;
b = --a;
assert(a == b);
a = 0;
b = a--;
assert(a != b);
assert(2 == 2);
assert(2 != 3);
assert(3 > 2);
assert(2 < 3);
assert(3 >= 3);
assert(2 <= 3);
List<dynamic> l = [1, 'a', 2, 'b'];
if (l[1] is String) {
l[1].toUpperCase();
}
(l[1] as String).toUpperCase();
a = 1;
b ??= 2;
a = 2;
a *= 3;
assert(a == 6);
var done = false;
var col = 3;
assert(!done && (col == 0 || col == 3));
final value = 0x22;
final bitmask = 0x0f;
assert((value & bitmask) == 0x02);
assert((value & ~bitmask) == 0x20);
assert((value | bitmask) == 0x2f);
assert((value ^ bitmask) == 0x2d);
assert((value << 4) == 0x220);
assert((value >> 4) == 0x02);
var isPublic = true;
var visibility = isPublic ? 'public' : 'private';
String playerName(String name) => name ?? 'Guest';
String playerNameArrow(String name) => name != null ? name : 'Guest';
String playerNameIf(String name) {
if (name != null) {
return name;
} else {
return 'Guest';
}
}
var sb = StringBuffer();
sb..write('foo')..write('bar');
// final addressBook = (AddressBookBuilder()
// ..name = 'jenny'
// ..email = 'jenny@example.com'
// ..phone = (PhoneNumberBuilder()
// ..number = '415-555-0100'
// ..label = 'home')
// .build())
// .build();
}
void main() {
var isRaining = false;
var isSnowing = true;
if (isRaining) {
print('bring rain coat');
} else if (isSnowing) {
print('wear jacket');
} else {
print('put top down');
}
var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
message.write('!');
}
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);
}
var isDone = false;
while (!isDone) {
print('do something');
isDone = true;
}
var atEndOfPage = true;
do {
print('do something');
} while (!atEndOfPage);
var shutDownRequested = true;
while (true) {
if (shutDownRequested) break;
print('process incoming requests');
}
var candidates = [1, 3, 5, 2, 4, 7];
for (int i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
if (candidate < 5) {
continue;
}
print('interview');
}
var command = 'OPEN';
switch (command) {
case 'CLOSED':
print('execute closed');
break;
case 'PENDING':
print('execute pending');
break;
case 'APPROVED':
print('execute approved');
break;
case 'DENIED':
print('execute denied');
break;
case 'OPEN':
print('execute open');
break;
default:
print('execute unknown');
}
var urlString = 'https://www.google.com/';
assert(urlString.startsWith('https'),
'URL ($urlString) should start with "https".');
}
void main() {
void foo() => throw UnimplementedError();
try {
foo();
} on UnimplementedError catch (e) {
print('Unknown exception: $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}
void misbehave() {
try {
dynamic foo = true;
print(foo++);
} catch (e) {
print('misbehave() partially handled ${e.runtimeType}.');
rethrow;
}
}
try {
misbehave();
} catch (e) {
print('main() finished handling ${e.runtimeType}.');
}
}
import 'dart:math';
class Point {
num x, y;
num distanceFromOrigin;
Point(this.x, this.y) : distanceFromOrigin = sqrt(x * x + y * y);
Point.origin() : this(0, 0);
Point.fromJson(Map<String, num> json) : this(json['x'], json['y']);
Point.withAssert(this.x, this.y)
: assert(x >= 0),
distanceFromOrigin = sqrt(x * x + y * y);
num distanceTo(Point other) {
var dx = x - other.x;
var dy = y - other.y;
return sqrt(dx * dx + dy * dy);
}
@override
String toString() => 'Point($x, $y)';
}
class ImmutablePoint {
static final origin = const ImmutablePoint(0, 0);
final num x, y;
const ImmutablePoint(this.x, this.y);
}
class Person {
String firstName;
Person.fromJson(Map data) {
print('in Person');
}
}
class Employee extends Person {
Employee.fromJson(Map data) : super.fromJson(data) {
print('in Employee');
}
}
class Logger {
final String name;
bool mute = false;
static final _cache = <String, Logger>{};
factory Logger(String name) {
if (_cache.containsKey(name)) {
return _cache[name];
} else {
final logger = Logger._internal(name);
_cache[name] = logger;
return logger;
}
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) print(msg);
}
}
class Rectangle {
num left, top, width, height;
Rectangle(this.left, this.top, this.width, this.height);
num get right => left + width;
set right(num value) => left = value - width;
num get bottom => top + height;
set bottom(num value) => top = value - height;
}
abstract class Doer {
void doSomething();
}
class EffectiveDoer extends Doer {
void doSomething() {
print('do something');
}
}
class Person1 {
final _name;
Person1(this._name);
String greet(String who) => 'Hello, $who. I am $_name.';
}
class Impostor implements Person1 {
get _name => '';
String greet(String who) => 'Hi $who. Do you know who I am?';
}
String greetBob(Person1 person) => person.greet('Bob');
class Television {
void turnOn() {
print('illuminate display');
print('activateIr sensor');
}
}
class SmartTelevision extends Television {
@override
void turnOn() {
super.turnOn();
print('illuminate display');
print('activateIr sensor');
print('upgrade apps');
}
}
class Vector {
final int x, y;
Vector(this.x, this.y);
Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
@override
int get hashCode {
int result = 17;
result = 37 * result + x.hashCode;
result = 37 * result + y.hashCode;
return result;
}
@override
bool operator ==(dynamic other) {
if (other is! Vector) return false;
Vector vector = other;
return (vector.x == x && vector.y == y);
}
}
class A {
@override
void noSuchMethod(Invocation invocation) {
print('You tried to use a non-existent member: ' +
'${invocation.memberName}');
}
}
void main() {
var p = Point(2, 2);
p.y = 3;
assert(p.y == 3);
num distance = p.distanceTo(Point(4, 4));
p?.y = 4;
var p1 = Point(2, 2);
var p2 = Point.fromJson({'x': 1, 'y': 2});
print(p2);
var ip = const ImmutablePoint(2, 2);
var a = const ImmutablePoint(1, 1);
var b = const ImmutablePoint(1, 1);
assert(identical(a, b));
const pointAndLine = {
'point': [ImmutablePoint(0, 0)],
'line': [ImmutablePoint(1, 10), ImmutablePoint(-2, 11)],
};
a = const ImmutablePoint(1, 1);
b = ImmutablePoint(1, 1);
assert(!identical(a, b));
print('The type of a is ${a.runtimeType}');
var emp = Employee.fromJson({});
if (emp is Person) {
emp.firstName = 'Bob';
}
(emp as Person).firstName = 'Bob';
var logger = Logger('UI');
logger.log('Button clicked');
var rect = Rectangle(3, 4, 20, 15);
assert(rect.left == 3);
rect.right = 12;
assert(rect.left == -8);
print(greetBob(Person1('Kathy')));
print(greetBob(Impostor()));
final v = Vector(2, 3);
final w = Vector(2, 2);
assert(v + w == Vector(4, 5));
assert(v - w == Vector(0, 1));
dynamic a1 = A();
a1.c();
}
abstract class ObjectCache {
Object getByKey(String key);
void setByKey(String key, Object value);
}
abstract class StringCache {
String getByKey(String key);
void setByKey(String key, String value);
}
abstract class Cache<T> {
T getByKey(String key);
void setByKey(String key, T value);
}
class Person {
String firstName;
Person.fromJson(Map data) {
print('in Person');
}
}
class Employee extends Person {
Employee.fromJson(Map data) : super.fromJson(data) {
print('in Employee');
}
}
class Foo<T extends Person> {
String toString() => "Instance of 'Foo<$T>'";
}
T first<T>(List<T> ts) {
T tmp = ts[0];
return tmp;
}
void main() {
var names = List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
// names.add(42);
names = <String>['Seth', 'Kathy', 'Lars'];
var pages = <String, String>{
'index.html': 'Homepage',
'robots.txt': 'Hints for web robots',
'humans.txt': 'We are people, not machines'
};
names = List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
var nameSet = Set<String>.from(names);
var views = Map<int, String>();
names = List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
print(names is List<String>);
var personFoo = Foo<Person>();
var employeeFoo = Foo<Employee>();
var foo = Foo();
print(foo);
// var objectFoo = Foo<Object>();
}
import 'dart:math';
// import 'dart:math' as m;
// import 'dart:math' show sqrt;
// import 'dart:math' deferred as m;
// Future sqrt(num n) async {
// await m.loadLibrary();
// m.sqrt(2);
// }
void main() {
print(sqrt(2));
}
import 'dart:async';
Future<String> lookUpVersion() async => '1.0.0';
Future checkVersion() async {
var version = await lookUpVersion();
print(version);
}
void main() async {
var version;
try {
version = await lookUpVersion();
} catch (e) {
print(e);
return;
}
print(version);
var s = Stream.fromIterable([1, 2, 3]);
await for (var v in s) {
print(v);
}
}
Iterable<int> naturalsTo(int n) sync* {
int k = 0;
while (k < n) yield k++;
}
Stream<int> asynchronousNaturalsTo(int n) async* {
int k = 0;
while (k < n) yield k++;
}
Iterable<int> naturalsDownFrom(int n) sync* {
if (n > 0) {
yield n;
yield* naturalsDownFrom(n - 1);
}
}
void main() async {
for (var v in naturalsTo(3)) {
print(v);
}
await for (var v in asynchronousNaturalsTo(3)) {
print(v);
}
for (var v in naturalsDownFrom(3)) {
print(v);
}
}
class WannabeFunction {
call(String a, String b, String c) => '$a $b $c!';
}
void main() {
var wf = WannabeFunction();
var out = wf("Hi", "there,", "gang");
print('$out');
}
class SortedCollection {
Function compare;
SortedCollection(int f(Object a, Object b)) {
compare = f;
}
}
int sort(Object a, Object b) => 0;
typedef Compare = int Function(Object a, Object b);
class SortedCollectionType {
Compare compare;
SortedCollectionType(this.compare);
}
typedef CompareGeneric<T> = int Function(T a, T b);
int sortInt(int a, int b) => a - b;
void main() {
var coll = SortedCollection(sort);
assert(coll.compare is Function);
var collType = SortedCollectionType(sort);
assert(collType.compare is Function);
assert(collType.compare is Compare);
assert(sortInt is CompareGeneric<int>);
}
class Television {
@deprecated
void activate() {
turnOn();
}
void turnOn() {
print('turn on');
}
}
class Todo {
final String who;
final String what;
const Todo(this.who, this.what);
}
@Todo('seth', 'make this do something')
void doSomething() {
print('do something');
}
void main() {
var tel = Television();
tel.activate();
doSomething();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment