{"id":9091,"date":"2022-06-19T18:38:03","date_gmt":"2022-06-19T16:38:03","guid":{"rendered":"https:\/\/via-internet.de\/blog\/?p=9091"},"modified":"2022-06-21T09:29:46","modified_gmt":"2022-06-21T07:29:46","slug":"dart-learning-dart","status":"publish","type":"post","link":"https:\/\/via-internet.de\/blog\/2022\/06\/19\/dart-learning-dart\/","title":{"rendered":"Dart | Learning Dart"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Creating a simple class<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Bicycle {\n  int cadence;\n  int _speed = 0;\n  int get speed => _speed;\n  int gear;\n\n  Bicycle(this.cadence, this.gear);\n\n  void applyBrake(int decrement) {\n    _speed -= decrement;\n  }\n\n  void speedUp(int increment) {\n    _speed += increment;\n  }\n\n  @override\n  String toString() => 'Bicycle: $_speed mph';\n}\n\nvoid main() {\n  var bike = Bicycle(2, 1);\n  print(bike);\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Using optional parameters<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import 'dart:math';\n\nclass Rectangle {\n  int width = 0;\n  int height = 0;\n  Point origin = Point(0, 0);\n\n  Rectangle({this.origin = const Point(0, 0), this.width = 0, this.height = 0});\n\n  @override\n  String toString() =>\n      'Origin: (${origin.x}, ${origin.y}), width: $width, height: $height';\n}\n\nmain() {\n  print(Rectangle(origin: const Point(10, 20), width: 100, height: 200));\n  print(Rectangle(origin: const Point(10, 10)));\n  print(Rectangle(width: 200));\n  print(Rectangle());\n}\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Create a factory<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import 'dart:math';\n\nabstract class Shape {\n  \/\/ Option 2: Create a factory constructor\n\n  factory Shape(String type) {\n    if (type == 'circle') return Circle(2);\n    if (type == 'square') return Square(2);\n    throw 'Can\\'t create $type.';\n  }\n\n  num get area;\n}\n\nclass Circle implements Shape {\n  final num radius;\n  Circle(this.radius);\n\n  @override\n  num get area => pi * pow(radius, 2);\n}\n\nclass Square implements Shape {\n  final num side;\n  Square(this.side);\n\n  @override\n  num get area => pow(side, 2);\n}\n\n\/\/ Option 1: Create a top-level function\nShape shapeFactory(String type) {\n  if (type == 'circle') return Circle(2);\n  if (type == 'square') return Square(2);\n  throw 'Can\\'t create $type.';\n}\n\nmain() {\n  \/\/ final circle = Circle(2);\n  \/\/ final square = Square(2);\n\n  \/\/ Option 1: Create a top-level function\n  \/\/ final circle = shapeFactory('circle');\n  \/\/ final square = shapeFactory('square');\n\n  \/\/ Option 2: Create a factory constructor\n  final circle = Shape('circle');\n  final square = Shape('square');\n  \n  print(circle.area);\n  print(square.area);\n}\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Implement an interface<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class CircleMock implements Circle {\n  num area = 0;\n  num radius = 0;\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Use Dart for functional programming<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">String scream(int length) => \"A${'a' * length}h!\";\n\nmain() {\n  final values = [1, 2, 3, 5, 10, 50];\n  for (var length in values) {\n    print(scream(length));\n  }\n  \n  \/\/ Functional\n  values.map(scream).forEach(print);\n}<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Language samples<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The following is copied from the<a rel=\"noreferrer noopener\" href=\"https:\/\/dart.dev\/samples\" data-type=\"URL\" data-id=\"https:\/\/dart.dev\/samples\" target=\"_blank\"> Dart Website.<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"hello-world\"><a href=\"https:\/\/dart.dev\/samples#hello-world\"><\/a>Hello World<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Every app has a&nbsp;<code>main()<\/code>&nbsp;function. To display text on the console, you can use the top-level&nbsp;<code>print()<\/code>&nbsp;function:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">void main() {\n  print('Hello, World!');\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"variables\"><a href=\"https:\/\/dart.dev\/samples#variables\"><\/a>Variables<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Even in type-safe Dart code, most variables don\u2019t need explicit types, thanks to type inference:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var name = 'Voyager I';\nvar year = 1977;\nvar antennaDiameter = 3.7;\nvar flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];\nvar image = {\n  'tags': ['saturn'],\n  'url': '\/\/path\/to\/saturn.jpg'\n};<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#variables\">Read more<\/a>&nbsp;about variables in Dart, including default values, the&nbsp;<code>final<\/code>&nbsp;and&nbsp;<code>const<\/code>&nbsp;keywords, and static types.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"control-flow-statements\"><a href=\"https:\/\/dart.dev\/samples#control-flow-statements\"><\/a>Control flow statements<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Dart supports the usual control flow statements:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">if (year >= 2001) {\n  print('21st century');\n} else if (year >= 1901) {\n  print('20th century');\n}\n\nfor (final object in flybyObjects) {\n  print(object);\n}\n\nfor (int month = 1; month &lt;= 12; month++) {\n  print(month);\n}\n\nwhile (year > 2016) {\n  year += 1;\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#control-flow-statements\">Read more<\/a>&nbsp;about control flow statements in Dart, including&nbsp;<code>break<\/code>&nbsp;and&nbsp;<code>continue<\/code>,&nbsp;<code>switch<\/code>&nbsp;and&nbsp;<code>case<\/code>, and&nbsp;<code>assert<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"functions\"><a href=\"https:\/\/dart.dev\/samples#functions\"><\/a>Functions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/effective-dart\/design#types\">We recommend<\/a>&nbsp;specifying the types of each function\u2019s arguments and return value:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int fibonacci(int n) {\n  if (n == 0 || n == 1) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nvar result = fibonacci(20);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A shorthand&nbsp;<code>=&gt;<\/code>&nbsp;(<em>arrow<\/em>) syntax is handy for functions that contain a single statement. This syntax is especially useful when passing anonymous functions as arguments:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">flybyObjects.where((name) => name.contains('turn')).forEach(print);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Besides showing an anonymous function (the argument to&nbsp;<code>where()<\/code>), this code shows that you can use a function as an argument: the top-level&nbsp;<code>print()<\/code>&nbsp;function is an argument to&nbsp;<code>forEach()<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#functions\">Read more<\/a>&nbsp;about functions in Dart, including optional parameters, default parameter values, and lexical scope.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"comments\"><a href=\"https:\/\/dart.dev\/samples#comments\"><\/a>Comments<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Dart comments usually start with&nbsp;<code>\/\/<\/code>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ This is a normal, one-line comment.\n\n\/\/\/ This is a documentation comment, used to document libraries,\n\/\/\/ classes, and their members. Tools like IDEs and dartdoc treat\n\/\/\/ doc comments specially.\n\n\/* Comments like these are also supported. *\/\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#comments\">Read more<\/a>&nbsp;about comments in Dart, including how the documentation tooling works.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"imports\"><a href=\"https:\/\/dart.dev\/samples#imports\"><\/a>Imports<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To access APIs defined in other libraries, use&nbsp;<code>import<\/code>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Importing core libraries\nimport 'dart:math';\n\n\/\/ Importing libraries from external packages\nimport 'package:test\/test.dart';\n\n\/\/ Importing files\nimport 'path\/to\/my_other_file.dart';<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#libraries-and-visibility\">Read more<\/a>&nbsp;about libraries and visibility in Dart, including library prefixes,&nbsp;<code>show<\/code>&nbsp;and&nbsp;<code>hide<\/code>, and lazy loading through the&nbsp;<code>deferred<\/code>&nbsp;keyword.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"classes\"><a href=\"https:\/\/dart.dev\/samples#classes\"><\/a>Classes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s an example of a class with three properties, two constructors, and a method. One of the properties can\u2019t be set directly, so it\u2019s defined using a getter method (instead of a variable).<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Spacecraft {\n  String name;\n  DateTime? launchDate;\n\n  \/\/ Read-only non-final property\n  int? get launchYear => launchDate?.year;\n\n  \/\/ Constructor, with syntactic sugar for assignment to members.\n  Spacecraft(this.name, this.launchDate) {\n    \/\/ Initialization code goes here.\n  }\n\n  \/\/ Named constructor that forwards to the default one.\n  Spacecraft.unlaunched(String name) : this(name, null);\n\n  \/\/ Method.\n  void describe() {\n    print('Spacecraft: $name');\n    \/\/ Type promotion doesn't work on getters.\n    var launchDate = this.launchDate;\n    if (launchDate != null) {\n      int years = DateTime.now().difference(launchDate).inDays ~\/ 365;\n      print('Launched: $launchYear ($years years ago)');\n    } else {\n      print('Unlaunched');\n    }\n  }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You might use the&nbsp;<code>Spacecraft<\/code>&nbsp;class like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));\nvoyager.describe();\n\nvar voyager3 = Spacecraft.unlaunched('Voyager III');\nvoyager3.describe();<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#classes\">Read more<\/a>&nbsp;about classes in Dart, including initializer lists, optional&nbsp;<code>new<\/code>&nbsp;and&nbsp;<code>const<\/code>, redirecting constructors,&nbsp;<code>factory<\/code>&nbsp;constructors, getters, setters, and much more.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"enums\"><a href=\"https:\/\/dart.dev\/samples#enums\"><\/a>Enums<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Enums are a way of enumerating a predefined set of values or instances in a way which ensures that there cannot be any other instances of that type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example of a simple&nbsp;<code>enum<\/code>&nbsp;that defines a simple list of predefined planet types:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">enum PlanetType { terrestrial, gas, ice }<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example of an enhanced enum declaration of a class describing planets, with a defined set of constant instances, namely the planets of our own solar system.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\/\/\/ Enum that enumerates the different planets in our solar system\n\/\/\/ and some of their properties.\nenum Planet {\n  mercury(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),\n  venus(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),\n  \/\/ \u00b7\u00b7\u00b7\n  uranus(planetType: PlanetType.ice, moons: 27, hasRings: true),\n  neptune(planetType: PlanetType.ice, moons: 14, hasRings: true);\n\n  \/\/\/ A constant generating constructor\n  const Planet(\n      {required this.planetType, required this.moons, required this.hasRings});\n\n  \/\/\/ All instance variables are final\n  final PlanetType planetType;\n  final int moons;\n  final bool hasRings;\n\n  \/\/\/ Enhanced enums support getters and other methods\n  bool get isGiant =&gt;\n      planetType == PlanetType.gas || planetType == PlanetType.ice;\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You might use the&nbsp;<code>Planet<\/code>&nbsp;enum like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">final yourPlanet = Planet.earth;\n\nif (!yourPlanet.isGiant) {\n  print('Your planet is not a \"giant planet\".');\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#enums\">Read more<\/a>&nbsp;about enums in Dart, including enhanced enum requirements, automatically introduced properties, accessing enumerated value names, switch statement support, and much more.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"inheritance\"><a href=\"https:\/\/dart.dev\/samples#inheritance\"><\/a>Inheritance<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Dart has single inheritance.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class Orbiter extends Spacecraft {\n  double altitude;\n\n  Orbiter(super.name, DateTime super.launchDate, this.altitude);\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#extending-a-class\">Read more<\/a>&nbsp;about extending classes, the optional&nbsp;<code>@override<\/code>&nbsp;annotation, and more.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"mixins\"><a href=\"https:\/\/dart.dev\/samples#mixins\"><\/a>Mixins<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Mixins are a way of reusing code in multiple class hierarchies. The following is a mixin declaration:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">mixin Piloted {\n  int astronauts = 1;\n\n  void describeCrew() {\n    print('Number of astronauts: $astronauts');\n  }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To add a mixin\u2019s capabilities to a class, just extend the class with the mixin.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class PilotedCraft extends Spacecraft with Piloted {\n  \/\/ \u00b7\u00b7\u00b7\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>PilotedCraft<\/code>&nbsp;now has the&nbsp;<code>astronauts<\/code>&nbsp;field as well as the&nbsp;<code>describeCrew()<\/code>&nbsp;method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#adding-features-to-a-class-mixins\">Read more<\/a>&nbsp;about mixins.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"interfaces-and-abstract-classes\"><a href=\"https:\/\/dart.dev\/samples#interfaces-and-abstract-classes\"><\/a>Interfaces and abstract classes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Dart has no&nbsp;<code>interface<\/code>&nbsp;keyword. Instead, all classes implicitly define an interface. Therefore, you can implement any class.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class MockSpaceship implements Spacecraft {\n  \/\/ \u00b7\u00b7\u00b7\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#implicit-interfaces\">Read more<\/a>&nbsp;about implicit interfaces.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can create an abstract class to be extended (or implemented) by a concrete class. Abstract classes can contain abstract methods (with empty bodies).<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">abstract class Describable {\n  void describe();\n\n  void describeWithEmphasis() {\n    print('=========');\n    describe();\n    print('=========');\n  }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Any class extending&nbsp;<code>Describable<\/code>&nbsp;has the&nbsp;<code>describeWithEmphasis()<\/code>&nbsp;method, which calls the extender\u2019s implementation of&nbsp;<code>describe()<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#abstract-classes\">Read more<\/a>&nbsp;about abstract classes and methods.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"async\"><a href=\"https:\/\/dart.dev\/samples#async\"><\/a>Async<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid callback hell and make your code much more readable by using&nbsp;<code>async<\/code>&nbsp;and&nbsp;<code>await<\/code>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">const oneSecond = Duration(seconds: 1);\n\/\/ \u00b7\u00b7\u00b7\nFuture&lt;void> printWithDelay(String message) async {\n  await Future.delayed(oneSecond);\n  print(message);\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The method above is equivalent to:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Future&lt;void&gt; printWithDelay(String message) {\n  return Future.delayed(oneSecond).then((_) {\n    print(message);\n  });\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As the next example shows,&nbsp;<code>async<\/code>&nbsp;and&nbsp;<code>await<\/code>&nbsp;help make asynchronous code easy to read.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Future&lt;void&gt; createDescriptions(Iterable&lt;String&gt; objects) async {\n  for (final object in objects) {\n    try {\n      var file = File('$object.txt');\n      if (await file.exists()) {\n        var modified = await file.lastModified();\n        print(\n            'File for $object already exists. It was modified on $modified.');\n        continue;\n      }\n      await file.create();\n      await file.writeAsString('Start describing $object in this file.');\n    } on IOException catch (e) {\n      print('Cannot create description for $object: $e');\n    }\n  }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also use&nbsp;<code>async*<\/code>, which gives you a nice, readable way to build streams.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"dart\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Stream&lt;String> report(Spacecraft craft, Iterable&lt;String> objects) async* {\n  for (final object in objects) {\n    await Future.delayed(oneSecond);\n    yield '${craft.name} flies by $object';\n  }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#asynchrony-support\">Read more<\/a>&nbsp;about asynchrony support, including&nbsp;<code>async<\/code>&nbsp;functions,&nbsp;<code>Future<\/code>,&nbsp;<code>Stream<\/code>, and the asynchronous loop (<code>await for<\/code>).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"exceptions\"><a href=\"https:\/\/dart.dev\/samples#exceptions\"><\/a>Exceptions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To raise an exception, use&nbsp;<code>throw<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">if (astronauts == 0) {\n  throw StateError('No astronauts.');\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To catch an exception, use a&nbsp;<code>try<\/code>&nbsp;statement with&nbsp;<code>on<\/code>&nbsp;or&nbsp;<code>catch<\/code>&nbsp;(or both):<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try {\n  for (final object in flybyObjects) {\n    var description = await File('$object.txt').readAsString();\n    print(description);\n  }\n} on IOException catch (e) {\n  print('Could not describe object: $e');\n} finally {\n  flybyObjects.clear();\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Note that the code above is asynchronous;&nbsp;<code>try<\/code>&nbsp;works for both synchronous code and code in an&nbsp;<code>async<\/code>&nbsp;function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour#exceptions\">Read more<\/a>&nbsp;about exceptions, including stack traces,&nbsp;<code>rethrow<\/code>, and the difference between&nbsp;<code>Error<\/code>&nbsp;and&nbsp;<code>Exception<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"other-topics\"><a href=\"https:\/\/dart.dev\/samples#other-topics\"><\/a>Other topics<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Many more code samples are in the&nbsp;<a href=\"https:\/\/dart.dev\/guides\/language\/language-tour\">language tour<\/a>&nbsp;and the&nbsp;<a href=\"https:\/\/dart.dev\/guides\/libraries\/library-tour\">library tour<\/a>. Also see the&nbsp;<a href=\"https:\/\/api.dart.dev\/\">Dart API reference,<\/a>&nbsp;which often contains examples.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"learn-more\">Learn more<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Articles<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/hackernoon.com\/why-flutter-uses-dart-dd635a054ebf\" target=\"_blank\" rel=\"noreferrer noopener\">Why Flutter uses Dart<\/a><\/li><li><a href=\"https:\/\/medium.com\/dartlang\/announcing-dart-2-80ba01f43b6\" target=\"_blank\" rel=\"noreferrer noopener\">Announcing Dart 2: Optimized for client-side development<\/a><\/li><li><a href=\"https:\/\/hackernoon.com\/why-i-moved-from-java-to-dart-8f3802b1d652\" target=\"_blank\" rel=\"noreferrer noopener\">Why I moved from Java to Dart<\/a><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Resources<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/dart.dev\/guides\/language\/language-tour\" target=\"_blank\" rel=\"noreferrer noopener\">A tour of the Dart language<\/a><\/li><li><a href=\"https:\/\/dart.dev\/guides\/libraries\/library-tour\" target=\"_blank\" rel=\"noreferrer noopener\">A tour of the core libraries<\/a><\/li><li><a href=\"https:\/\/dart.dev\/guides\/language\/effective-dart\" target=\"_blank\" rel=\"noreferrer noopener\">Effective Dart<\/a><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Websites<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/dart.dev\/\" target=\"_blank\" rel=\"noreferrer noopener\">dart.dev: The Dart programming language<\/a><\/li><li><a href=\"https:\/\/flutter.dev\/\" target=\"_blank\" rel=\"noreferrer noopener\">flutter.dev: The Flutter UI toolkit<\/a><\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Creating a simple class Using optional parameters Create a factory Implement an interface Use Dart for functional programming Language samples The following is copied from the Dart Website. Hello World Every app has a&nbsp;main()&nbsp;function. To display text on the console, you can use the top-level&nbsp;print()&nbsp;function: Variables Even in type-safe Dart code, most variables don\u2019t need explicit types, thanks to type inference: Read more&nbsp;about variables in Dart, including default values, the&nbsp;final&nbsp;and&nbsp;const&nbsp;keywords, and static types. Control flow statements Dart supports the usual control flow statements: Read more&nbsp;about control flow statements in Dart, including&nbsp;break&nbsp;and&nbsp;continue,&nbsp;switch&nbsp;and&nbsp;case, and&nbsp;assert. Functions We recommend&nbsp;specifying the types of each function\u2019s [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":9101,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[26,49],"tags":[],"class_list":["post-9091","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-flutter","category-mobile-development"],"jetpack_featured_media_url":"https:\/\/via-internet.de\/blog\/wp-content\/uploads\/2022\/06\/dart_header.png","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/posts\/9091","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/comments?post=9091"}],"version-history":[{"count":5,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/posts\/9091\/revisions"}],"predecessor-version":[{"id":9104,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/posts\/9091\/revisions\/9104"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/media\/9101"}],"wp:attachment":[{"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/media?parent=9091"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/categories?post=9091"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/via-internet.de\/blog\/wp-json\/wp\/v2\/tags?post=9091"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}