Dart: Unterschied zwischen den Versionen

Aus Info-Theke
Zur Navigation springen Zur Suche springen
Zeile 7: Zeile 7:


= Statements =
= Statements =
<pre>for (var ix in list) {}
<source lang=dart>for (var ix in list) {}
for (int ix = 0; ix < 10; ix++) {}
for (int ix = 0; ix < 10; ix++) {}
while (doIt()){ }
while (doIt()){ }
Zeile 19: Zeile 19:
}
}
assert(str.isEmpty(), "String muss leer sein"); // nur im Debug aktiv.
assert(str.isEmpty(), "String muss leer sein"); // nur im Debug aktiv.
</pre>
</source>
== Exception ==
== Exception ==
<pre>
<source lang=dart>
try {
try {
   breedMoreLlamas();
   breedMoreLlamas();
Zeile 39: Zeile 39:
   MyException(this.message);
   MyException(this.message);
}
}
</pre>
</source>


= Class =
= Class =
<pre>abstract class BaseLogger {
<source lang=dart>abstract class BaseLogger {
   int _errors = 0;
   int _errors = 0;
   int _level;
   int _level;
Zeile 63: Zeile 63:
   var logger = Logger('std.log'), logger2 = Logger.silentLogger('silent.log');
   var logger = Logger('std.log'), logger2 = Logger.silentLogger('silent.log');
   const logger2 = BaseLogger.lastInstance();
   const logger2 = BaseLogger.lastInstance();
</pre>
</source>
== Interface ==
== Interface ==
* Jede Klasse kann Interface sein. Dann muss jede Methode überschrieben werden
* Jede Klasse kann Interface sein. Dann muss jede Methode überschrieben werden
<pre>
<source lang=dart>
class D implements A, B, C {
class D implements A, B, C {
   @override
   @override
Zeile 73: Zeile 73:
   }
   }
}
}
</pre>
</source>


== Generator ==
== Generator ==
<pre>Iterable<int> naturalsTo(int n) sync* {
<source lang=dart>Iterable<int> naturalsTo(int n) sync* {
   int k = 0;
   int k = 0;
   while (k < n) yield k++;
   while (k < n) yield k++;
}
}
</pre>
</source>
* ... und mit Rekursion:
* ... und mit Rekursion:
<pre>Iterable<int> naturalsDownFrom(int n) sync* {
<source lang=dart>Iterable<int> naturalsDownFrom(int n) sync* {
   if (n > 0) {
   if (n > 0) {
     yield n;
     yield n;
Zeile 88: Zeile 88:
   }
   }
}
}
</pre>
</source>


= Map =
= Map =
<pre>final map = <String, int>{ 'John': 1, 'Eve': 2 };
<source lang=dart>final map = <String, int>{ 'John': 1, 'Eve': 2 };
final knowsEve = map.containsKey('Eve') && map.containsValue(2);
final knowsEve = map.containsKey('Eve') && map.containsValue(2);
map.remove('John');
map.remove('John');
Zeile 98: Zeile 98:
map.forEach((k, v) { print('{ key: $k, value: $v }'); });
map.forEach((k, v) { print('{ key: $k, value: $v }'); });
map.entries.forEach((e) {  print('{ key: ${e.key}, value: ${e.value} }'); });
map.entries.forEach((e) {  print('{ key: ${e.key}, value: ${e.value} }'); });
</pre>
</source>


= List =
= List =
* Indizes: start: inklusiv end: exklusiv
* Indizes: start: inklusiv end: exklusiv
<pre>final names = <String>['adam', 'bob', 'charly', 'eve'];
<source lang=dart>final names = <String>['adam', 'bob', 'charly', 'eve'];
names.add('fred');
names.add('fred');
ix = names.indexOf('bob'); ix2 = names.indexWhere((item) => item.startsWith('b'), start);
ix = names.indexOf('bob'); ix2 = names.indexWhere((item) => item.startsWith('b'), start);
Zeile 118: Zeile 118:
// fold(), reduce(), shuffle(), removeWhere(),
// fold(), reduce(), shuffle(), removeWhere(),
// foreach(), join(), contains()
// foreach(), join(), contains()
</pre>
</source>


= DateTime =
= DateTime =
<pre>var now = new DateTime.now();
<source lang=dart>var now = new DateTime.now();
var moonLanding = DateTime.parse("1969-07-20 20:18:04Z");
var moonLanding = DateTime.parse("1969-07-20 20:18:04Z");
var sixtyDaysFromNow = now.add(new Duration(days: 60));
var sixtyDaysFromNow = now.add(new Duration(days: 60));
Zeile 133: Zeile 133:
var formatter = new DateFormat('yyyy.MM.dd HH:mm:ss dayOfWeek: E');
var formatter = new DateFormat('yyyy.MM.dd HH:mm:ss dayOfWeek: E');
String formatted = formatter.format(now);
String formatted = formatter.format(now);
</pre>
</source>


= RegExpr =
= RegExpr =
<pre>final regExpr = RegExp(r'(\w+)\s*=\s*(\d+)');
<source lang=dart>final regExpr = RegExp(r'(\w+)\s*=\s*(\d+)');
final matcher = reDisks.firstMatch(line);
final matcher = reDisks.firstMatch(line);
if (matcher != null){
if (matcher != null){
   vars[matcher.group(1)] = int.parse(matcher.group(2));
   vars[matcher.group(1)] = int.parse(matcher.group(2));
}
}
</pre>
</source>


= String =
= String =
<source lang=dart>
const limit = 3;
var interpreted = "Limit: $limit Time: ${time()}";
</source>
== Konversion ==
== Konversion ==
<pre>final count = int.parse("123");
<source lang=dart>final count = int.parse("123");
</pre>
</source>


== Formatierung ==
== Formatierung ==
<pre>import 'package:sprintf/sprintf.dart';
<source lang=dart>import 'package:sprintf/sprintf.dart';
sprintf("%02d %s", [1, "Hi"]);
sprintf("%02d %s", [1, "Hi"]);
print("${new DateTime.now().toString()}: $message\n");
print("${new DateTime.now().toString()}: $message\n");
</pre>
</source>


= Besonderheiten =
= Besonderheiten =
* entweder optionale Positionsparameter oder optionale Namensparameter, nicht beide.
* entweder optionale Positionsparameter oder optionale Namensparameter, nicht beide.
<pre>String substr(String str, int pos, [int length, bool uppercase]){ ... }
<source lang=dart>String substr(String str, int pos, [int length, bool uppercase]){ ... }
<pre>String substr2(String str, int pos, {int length, bool uppercase, Logger logger}){ ... }
String substr2(String str, int pos, {int length, bool uppercase, Logger logger}){ ... }
x = substr('Hi world', 3, 2);
x = substr('Hi world', 3, 2);
y = substr2('Hi world', 3, length:2, logger:logger);
y = substr2('Hi world', 3, length:2, logger:logger);
</pre>
// ..-Operator: Mehrfachzugriff auf voriges Objekt:
* ..-Operator: Mehrfachzugriff auf voriges Objekt:
var person = Person()..name='Joe'..id=25;
<pre>var person = Person()..name='Joe'..id=25;
var p = Point(10, -12)..setColor(green)..setWeight(1.22);
var p = Point(10, -12)..setColor(green)..setWeight(1.22);
</pre>
x ??= 5; // Zuweisung nur, wenn x==null
* x ??= 5; // Zuweisung nur, wenn x==null
x ~/ 5 // Ganzzahlige Division
* x ~/ 5 // Ganzzahlige Division
logger?.log() // Aufruf von log nur, wenn logger!=null
* logger?.log() // Aufruf von log nur, wenn logger!=null
</source>


== Reflection, Runtime-Info ==
== Reflection, Runtime-Info ==
<pre>if (a.runtimeType == int || a.runtimeType == String)...
<source lang=dart>if (a.runtimeType == int || a.runtimeType == String)...
</pre>
</source>

Version vom 22. September 2020, 10:01 Uhr


Links

Statements

for (var ix in list) {}
for (int ix = 0; ix < 10; ix++) {}
while (doIt()){ }
do { } while(test());
switch(x) { 
  case '0':
  case 'A': y=3; break;
  case 'B': b=true; continue on_label_c; // Implementierung von "fall through"
  on_label_c: case 'C': y=5; break;
  default: break; 
}
assert(str.isEmpty(), "String muss leer sein"); // nur im Debug aktiv.

Exception

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  buyMoreLlamas();
} on Exception catch (e) {
  print('Unknown exception: $e'); // Anything else that is an exception
} catch (e, stacktrace) {
  print('Something really unknown: $e $stacktrace'); // No specified type, handles all
  rethrow; // throw the same exception again
} finally {
  cleanUp();
}
throw ArgumentError('not an int');
class MyException implements Exception{
  String message;
  MyException(this.message);
}

Class

abstract class BaseLogger {
  int _errors = 0;
  int _level;
  static BaseLogger _lastInstance;
  bool get isSilent => _level == 0; // getter
  set isSilent(bool value) => _level = value ? 0 : 1; // setter
  BaseLogger(this._level); // constructor
  BaseLogger.silent() : this(0); // named constructor, "redirected constructor"
  // abstract function:
  void log(string message);
  void error(string message){ _errors++; log('+++ ' + message); }
  static BaseLogger lastInstance() { return _lastInstance; }
}
class Logger extends BaseLogger {
  String _filename;
  Logger(this._filename) : super(1);
  Logger.silentLogger(this._filename) : super.silent(0); // named constructor
}
...
  var logger = Logger('std.log'), logger2 = Logger.silentLogger('silent.log');
  const logger2 = BaseLogger.lastInstance();

Interface

  • Jede Klasse kann Interface sein. Dann muss jede Methode überschrieben werden
class D implements A, B, C {
  @override
  void doIt(){
    // ...
  }
}

Generator

Iterable<int> naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}
  • ... und mit Rekursion:
Iterable<int> naturalsDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* naturalsDownFrom(n - 1);
  }
}

Map

final map = <String, int>{ 'John': 1, 'Eve': 2 };
final knowsEve = map.containsKey('Eve') && map.containsValue(2);
map.remove('John');
map.removeWhere((k, v) => k.startsWith('J'));
final combinedMap1 = {...map1, ...map2};
map.forEach((k, v) { print('{ key: $k, value: $v }'); });
map.entries.forEach((e) {  print('{ key: ${e.key}, value: ${e.value} }'); });

List

  • Indizes: start: inklusiv end: exklusiv
final names = <String>['adam', 'bob', 'charly', 'eve'];
names.add('fred');
ix = names.indexOf('bob'); ix2 = names.indexWhere((item) => item.startsWith('b'), start);
names.remove('bob'); names.removeAt(2);
names2 = names.getRange(2, 3);
name3 = names.sublist(ixStart, ixEnd);
print(names.first + ' ' + names.last);
names.firstWhere( (item) => item.length == 3);
names.replaceRange(1,3, ['john', 'judith']);
final first2Elements = names.take(2);
final allButFirst2Elements = names.skip(2);
names.followedBy(name2); // liefert names und die Iterables name2
names.any((item) => item.length < 3); // irgend ein Element mit der Bedingung
names.every((item) => item.length < 3); // alle Elemente mit der Bedingung
// fold(), reduce(), shuffle(), removeWhere(),
// foreach(), join(), contains()

DateTime

var now = new DateTime.now();
var moonLanding = DateTime.parse("1969-07-20 20:18:04Z");
var sixtyDaysFromNow = now.add(new Duration(days: 60));
final diffDays = sixtyDaysFromNow.difference(moonLanding).inDays;
var dateUtc = new DateTime.utc(1944, 6, 6);
var local = dateUts.toLocal();
var isBefore = now.before(sixtyDaysFromNow);

var linuxTime = now.millisecondsSinceEpoch ~/ 1000;

var formatter = new DateFormat('yyyy.MM.dd HH:mm:ss dayOfWeek: E');
String formatted = formatter.format(now);

RegExpr

final regExpr = RegExp(r'(\w+)\s*=\s*(\d+)');
final matcher = reDisks.firstMatch(line);
if (matcher != null){
  vars[matcher.group(1)] = int.parse(matcher.group(2));
}

String

const limit = 3;
var interpreted = "Limit: $limit Time: ${time()}";

Konversion

final count = int.parse("123");

Formatierung

import 'package:sprintf/sprintf.dart';
sprintf("%02d %s", [1, "Hi"]);
print("${new DateTime.now().toString()}: $message\n");

Besonderheiten

  • entweder optionale Positionsparameter oder optionale Namensparameter, nicht beide.
String substr(String str, int pos, [int length, bool uppercase]){ ... }
String substr2(String str, int pos, {int length, bool uppercase, Logger logger}){ ... }
x = substr('Hi world', 3, 2);
y = substr2('Hi world', 3, length:2, logger:logger);
// ..-Operator: Mehrfachzugriff auf voriges Objekt:
var person = Person()..name='Joe'..id=25;
var p = Point(10, -12)..setColor(green)..setWeight(1.22);
x ??= 5; // Zuweisung nur, wenn x==null
x ~/ 5 // Ganzzahlige Division
logger?.log() // Aufruf von log nur, wenn logger!=null

Reflection, Runtime-Info

if (a.runtimeType == int || a.runtimeType == String)...