{"id":13494855,"url":"https://github.com/dwyl/learn-dart","last_synced_at":"2025-04-09T16:05:13.970Z","repository":{"id":56082867,"uuid":"232620554","full_name":"dwyl/learn-dart","owner":"dwyl","description":"🎯Learn the Dart programming language to build cross-platform (Mobile, Web \u0026 Desktop) Apps with Flutter!","archived":false,"fork":false,"pushed_at":"2022-12-06T10:39:39.000Z","size":90,"stargazers_count":37,"open_issues_count":12,"forks_count":9,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-09T16:05:02.629Z","etag":null,"topics":["beginner","dart","dart-lang","learn","learning","tutorial"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dwyl.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-01-08T17:32:37.000Z","updated_at":"2025-04-06T14:39:32.000Z","dependencies_parsed_at":"2023-01-23T07:20:21.364Z","dependency_job_id":null,"html_url":"https://github.com/dwyl/learn-dart","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dwyl%2Flearn-dart","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dwyl%2Flearn-dart/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dwyl%2Flearn-dart/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dwyl%2Flearn-dart/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dwyl","download_url":"https://codeload.github.com/dwyl/learn-dart/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248065289,"owners_count":21041871,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["beginner","dart","dart-lang","learn","learning","tutorial"],"created_at":"2024-07-31T19:01:28.856Z","updated_at":"2025-04-09T16:05:13.941Z","avatar_url":"https://github.com/dwyl.png","language":null,"readme":"\u003cdiv align=\"center\"\u003e\n\n![learn-dart-hero-image](https://user-images.githubusercontent.com/194400/84486386-40790900-ac95-11ea-916b-e27c1d141056.png \"Learn Dart intro image\")\n\nLearn the [`Dart`](https://dart.dev) programming language \nto build cross-platform Native (Mobile, Web and Desktop) Apps \nwith [`Flutter`](https://github.com/dwyl/learn-flutter)!\n\n\u003cbr /\u003e\n\u003c/div\u003e\n\n- [What ?](#what-)\n- [Who?](#who)\n- [How?](#how)\n  - [Install `Dart`](#install-dart)\n    - [Mac](#mac)\n    - [Linux](#linux)\n    - [Windows?](#windows)\n  - [`Hello World!`](#hello-world)\n  - [Basic Variables](#basic-variables)\n    - [Using the `var` Keyword](#using-the-var-keyword)\n  - [`Dart` Syntax:](#dart-syntax)\n    - [Variables](#variables)\n      - [The keyword `var`](#the-keyword-var)\n      - [Types](#types)\n      - [The `final` keyword](#the-final-keyword)\n      - [The `const` keyword](#the-const-keyword)\n      - [The `dynamic` keyword](#the-dynamic-keyword)\n      - [The `late` keyword](#the-late-keyword)\n        - [Declaring a non-nullable variable that’s initialized after its declaration.](#declaring-a-non-nullable-variable-thats-initialized-after-its-declaration)\n        - [Lazily initializing a variable.](#lazily-initializing-a-variable)\n    - [`main()` function](#main-function)\n    - [Arrow functions](#arrow-functions)\n    - [Named parameters](#named-parameters)\n  - [Asynchronous events](#asynchronous-events)\n  - [Object-Oriented Programming in Dart](#object-oriented-programming-in-dart)\n    - [Constructor](#constructor)\n    - [Initializer list](#initializer-list)\n    - [inheritance](#inheritance)\n    - [abstract class](#abstract-class)\n    - [Class interface with `implements`](#class-interface-with-implements)\n  - [Useful tools to use with Flutter](#useful-tools-to-use-with-flutter)\n  - [Dartanalyzer](#dartanalyzer)\n  - [Linting](#linting)\n  - [`Dart` Testing](#dart-testing)\n  - [Types of Tests](#types-of-tests)\n    - [Unit Tests](#unit-tests)\n    - [Component Tests](#component-tests)\n    - [End-To-End Tests](#end-to-end-tests)\n  - [Useful libraries in Dart](#useful-libraries-in-dart)\n  - [Publishing Packages to `pub.dev`](#publishing-packages-to-pubdev)\n  - [`Dart` VS Javascript:](#dart-vs-javascript)\n\n\n\n## Why?\n\n`Dart` is a general purpose programming language\nthat can be used for Servers, Client Apps, \n**_Native_ Mobile Apps**\nand _everything_ in between!\nGoogle uses `Dart` for several of their high profile products/projects\nincluding Google Assistant (Client), Google Home Hub\nand the Google Ads Platform (_their main money maker_).\n\n`Dart` lets you build Apps for _any_ platform\nwith a native interface/experience and performance.\nIf you want to build cross-platform _Native_ Mobile Apps \nthat don't waste memory or drain the devices' battery,\nuse `Dart` and `Flutter`.\n\n\nAccording to GitHub in 2019, \nthe biggest developer community,\n`Dart` is fastest growing programming language:\nhttps://octoverse.github.com/#top-languages\n\n![github-top-programming-languages](https://user-images.githubusercontent.com/194400/84571947-b44b0c80-ad8e-11ea-8089-de0672e9e6d1.png)\n\nThis is because, as of 2019, `Flutter` was the second fastest growing project on GitHub:\nhttps://octoverse.github.com/#top-and-trending-projects\n\n![flutter-to-trending-project](https://user-images.githubusercontent.com/194400/84572723-e3b04800-ad93-11ea-85e2-19e9693e5a26.png)\n\nIn 2019, `Flutter` has inclusively \novertaken React Native\nin Google search frequency and\nhas maintained this trend ever since:\n[https://trends.google.com/trends/explore](https://trends.google.com/trends/explore?date=today%205-y\u0026q=%2Fg%2F11f03_rzbg,react%20native)\n\n\u003cimg width=\"1373\" alt=\"google-trends-graph-flutter-v-react-native\" src=\"https://user-images.githubusercontent.com/17494745/198244948-29e5d3a5-1b2b-4d1f-a434-d4eee2a5799c.png\"\u003e\n\n\nThe Flutter GitHub repository: https://github.com/flutter/flutter has more Starts (_a good measure of popularity_):\n\nFlutter Stars           |  Flutter Languages\n:-------------------------:|:-------------------------:\n![flutter_stars](https://user-images.githubusercontent.com/17494745/198246297-2aafe6ea-0810-4c3a-b864-653ae3f72546.png)  |  ![flutter_languages](https://user-images.githubusercontent.com/17494745/198246641-792d7f4a-d025-4035-a204-3289962bade4.png)\n\n\nAdditionally an important metric to consider \nis the fact that **99%** of the code for `Flutter`\nis written in `Dart` which means anyone who knows `Dart` \ncan read, understand and _contribute_ to it.\n\nBy contrast React Native https://github.com/facebook/react-native \nhas fewer stars (_even though it's been available for longer_):\n\nReact Native Stars           |  React Native Languages\n:-------------------------:|:-------------------------:\n![rn_stars](https://user-images.githubusercontent.com/17494745/198247220-6f9d44c0-bfbb-4850-a47a-6459798b3285.png)  |  ![rn_languages](https://user-images.githubusercontent.com/17494745/198247332-d986d36c-d354-4367-a7bf-7c7bb0a8856c.png)\n\n\nAnd RN is written in 5 programming languages! \nSo anyone wanting to contribute a truly cross-platform UI feature \nneeds to know at least `JavaScript`, `Java` and `Objective-C`.\nBut since there are two _other_ flavours of `C` (namely `C++` and `Objective-C++`)\nused in RN, you will need to go digging for whichm one. \nIf you need to _debug_ why a particular UI does not work _consistenly_\nacross various Android versions or between iOS devices,\nyou need to dig into the `Objective-C` to understand it.\n\nYou don't have that headache in `Flutter`, everything is written in `Dart`.\nThe comparatively _tiny_ amount of `Java` and `Objective-C`\n\nIt's a _no-brainer_ to Learn `Dart` and `Flutter`. \n`Flutter` will _inevitably_ win the Cross-platform Native Mobile App \"war\"\nbecause it has `Dart` as it's foundation. \n\n\n\n\n\n\nIt's worth paying attention to these growth stats.\n\n\n\nLet's face it, you're not reading this because you want\nto learn another general purpose language. \nFor that you would learn/use `Python` or `JavaScript`.\nYou are here for the same reason as we are,\nto learn `Dart` as fast as possible,\nso that you can use `Flutter` to build Native Apps. \n\n\n\nYou are here for the same reason as us,\nto learn `Dart` as fast as possible,\nso that you can build `Flutter` Apps.\n\nBecause you very few people are using `Dart` outside of `Flutter`;\nanyone that needs _general purpose_ programming laguage uses `Python`.\nIf you want to build `Flutter` Apps, learn `Dart`;\nthis tutorial is the perfect place to start.\n\n\n# What ?\n\n`Dart` is an open-source general-purpose programming language.\nIt can be compiled to run as high performance JavaScript in web browsers,\nor as a native app on mobile (iOS + Android)\nand desktop.\n\nIt's an object-oriented language with C-style syntax\nfamiliar to all developers who have used\nan Object Oriented Programming (OOP) \nlanguage (e.g. `JavaScript`, `Java`, `C++`, `C#`, `Go`, etc.).\nIt supports a varied range of programming aids like interfaces,\nclasses, collections, generics, and optional typing.\nDon't worry if these terms are unfamilar right now,\nyou will learn their use through examples below.\n\n`Dart` was created by Lars Bak and Kasper Lund\nwhile working for Google.\n`Dart` was made an official standard by\nthe European Computer Manufacturers Association\n[ECMA 408](https://www.ecma-international.org/publications/standards/Ecma-408.htm) in 2015.\nThe language syntax and semantics are **stable**.\n\n\n\n\nRead more:\n\n+ Official guides:\nhttps://dart.dev/guides\n+ Wikipedia article has the history:\nhttps://en.wikipedia.org/wiki/Dart_(programming_language)\n\n\n# Who?\n\nThis tutorial is for anyone who wants to learn `Dart` from scratch\nwithout any prior knowledge of other programming languages.\n\nLearning `Dart` is a prerequisite \nfor building cross-platform native mobile/desktop/web Apps \nwith `Flutter`.\n\n\n\u003cbr /\u003e\n\n# How?\n\nWe recommend that you `clone` this Git repository \nso that you can follow along on your `localhost`\n_offline_:\n\n```sh\ngit clone git@github.com:dwyl/learn-dart.git \u0026\u0026 cd learn-dart\n```\n\n\u003e **Note**: If you are unable to run code on your device \n(e.g. you're reading this on an iPad), \u003cbr /\u003e\nall examples have a link to \n**Dart Pad** so you can try them online:\nhttps://dartpad.dartlang.org\n\n\n\u003cbr /\u003e\n\n## Install `Dart`\n\nThe official installation instructions are:\nhttps://dart.dev/get-dart\n\n\n### Mac\n\nThe recommended approach is to use Homebrew \n[brew.sh](https://brew.sh)\n\n```sh\nbrew tap dart-lang/dart\nbrew install dart\n```\n\n### Linux\n\nFollow the official instructions \nfor your version of Linux: \nhttps://dart.dev/get-dart\n\n\n### Windows?\n\nInstall the Flutter SDK which includes Dart:\nhttps://flutter.dev/docs/get-started/install/windows\n\n\u003c!-- \nWe don't *want* detailed Windows installation instructions \nbecause we don't *use* windows for any development work. \nRead: https://www.gnu.org/proprietary/malware-microsoft.html\nAnyone using Windows for should install/dual-boot Linux. \nYes, Mac is also proprietary, but it's not actively malicious.\n--\u003e\n\n\u003cbr /\u003e\n\nOnce you have `Dart` installed, \nif you run the following terminal command:\n\n```sh\ndart --version\n```\n\nYou should see something similar to:\n\n```sh\nDart VM version: 2.8.4 (stable) (Wed Jun 3 12:26:04 2020 +0200) on \"macos_x64\"\n```\n\n\u003e You may have more _recent_ version of `Dart`; that's fine!\n\n\n\u003e Since Dart is primarily used in building\nFlutter applications, it might make sense for you\nto follow the \n[Flutter install guide](https://docs.flutter.dev/get-started/install),\nwhich will help you install Flutter which, in turn,\nhave the Flutter SKD embedded.\n\n\n\u003cbr /\u003e\n\n## `Hello World!`\n\nOnce you have installed `Dart` on your `localhost` \n(_or opened [Dart Pad](https://dartpad.dartlang.org) \nif you are unable to install it on your mobile device_),\nopen your text \n[editor of choice](https://github.com/dwyl/dev-setup/issues/37),\ncreate a directory called [`/examples`]()\nand _inside_ that directory,\ncreate a file with path \n[`examples/hello.dart`]()\n\nThen _type_ the following code:\n\n```dart\nmain() {\n  print('Hello World!');\n}\n```\n\ne.g: \n\n\nThis code creates a function called `main` \nwhich calls `print` \nwith our desired `String` `'Hello World!'`.\nThe function does not _return_ anything \n\n\nNow in your terminal window,\nexecute the program by typing: \n\n```sh\ndart examples/hello.dart\n```\n\nYou should see:\n\n```\nHello World!\n```\n\n\u003e Try it: https://dartpad.dartlang.org/fa6f6e5a7b9406e88b31a17e82655ef8\n\n![dart-pad-hello-world-example](https://user-images.githubusercontent.com/194400/84514887-a54b5800-acc3-11ea-80bf-4ca4f39d1869.png)\n\n\n\u003cbr /\u003e\n\nBy convention, you will often see the `main` function \nprefixed with the `void` keyword/type, e.g:\n\n```dart\nvoid main() {\n  print('Hello World!');\n}\n```\n\nThis just means that our `main` function will not return anything.\nIn this case it's safe to ommit the `void` keywork \nas it is in _inferred_ by the compiler.\nWe checked: \nhttps://stackoverflow.com/questions/62346301/does-dart-main-function\n\n\u003e If see the `void` keyword and are curious about it, read: \u003cbr /\u003e\n\u003e + https://en.wikipedia.org/wiki/Void_type\n\u003e + https://medium.com/flutter-community/the-curious-case-of-void-in-dart-f0535705e529\n\u003e + https://medium.com/dartlang/dart-2-legacy-of-the-void-e7afb5f44df0\n\n\u003cbr /\u003e\n\n## Basic Variables \n\nThe next thing you need to know in `Dart` \nis how to create variables (_or constants_)\nto store your data.\n\n### Using the `var` Keyword\n\nThe most basic way of defining variables \nis using the `var` keyword.\nCreate a new file with the path:\n[`examples/var.dart`]()\nand type the following code in it:\n\n```dart\nmain() {\n  var name = 'Alex'; // or whatever your name is! \n  print('Hello $name'); \n}\n```\nChange the _value_ `name` to whatever your name is.\n\nOnce you have saved the file,\nrun it with the command:\n\n```sh\ndart examples/var.dart\n```\n\nYou should see output similar to the following:\n\n```\nHello Alex!\n```\n\n\u003e Try it: https://dartpad.dartlang.org/560f88da44b108ffe34e6979079246ea\n\n![dart-pad-variables-example](https://user-images.githubusercontent.com/194400/84532536-4e9f4780-acde-11ea-9bfd-7f6f0c8bcb1b.png)\n\n\n_Explanation_ of the code:\n+ `main() {` - is familiar from the previous example,\nit's the top-level function that dart invokes to run the program.\n+ `var name = 'Alex';` - this is our variable definition using the `var` keyword. We _assign_ the value `'Alex'` \nto the variable `name`. \n+ `print('Hello $name');` - prints the `String` `'Hello` \nfollowed by the variable `name` we defined on the previous line.\nThe inclusion of the `$` (dollar sign) in the `$name` \nis the way to include a variable inside the `String`.\nThis is knonw as \n[String interpolation](https://dart.dev/guides/language/language-tour#strings).\n\n\n## `Dart` Syntax:\n\nSyntax is reasonably concise compared to other languages like `Java` or `JavaScript`.\n\ndefines a set of rules for writing programs.\nA `Dart` program is composed of:\n\n+ Variables and Operators\n+ Classes\n+ Functions\n+ Expressions and Programming Constructs\n+ Decision Making and Looping Constructs\n+ Comments\n+ Libraries and Packages\n\n\u003cbr /\u003e\n\n### Variables\n\nThere are several ways to define variables in Dart:\n\n#### The keyword `var`\n\n```dart\nvar a;\na = 42;\n```\n\nIn this example the variable `a` is first declared,\nthen initialised on the next line.\n\nIn the following example we attempt to\nre-assign the variable `a` to a `String`,\nhowever since\n`Dart`\n[statically typed](https://dart.dev/faq#q-is-dart-a-statically-typed-language),\nthe code won't compile.\n`a` is initialised as an `int`,\nso attempting to reassign it as `String`\non the next line will fail:\n\n**error**\n```dart\nvar a = 42;\na = 'hello';\n```\n\nYou will see the following error:\n\n```dart\nError: A value of type 'String' can't be assigned to a variable of type 'int'.\n  a = 'hello';\n      ^\nError: Compilation failed.\n```\n\ne.g: https://dartpad.dartlang.org/bea94fb6dec3a69799f1f040135489a0\n\n#### Types\n\n```dart\nint a;\na = 42;\na = 52;\n```\n\nA type name can be used to create variables.\nIn this example `a` is declared with the type `int`,\nthen the value `42` is assigned to `a`.\nOn the last line `a` is assigned a new `int` value.\n\nIt is also possible to declare and assign a value to a variable at the same time:\n\n```dart\nint a = 42;\n```\n\nHowever `Dart` will produce an error if multiple assignements are done\nwith different type of values:\n\n```dart\nint a;\na = 42;\na = 'hello'; //error as a is defined to only be assigned with a value of type int\n```\n\nUnless you explicitly tell Dart that \na variable can be `null`, every variable you \ndeclare is considered **non-nullabe**. \n_However_, even though null safety is used\nby default with Dart, you can indicate that a \nvariable might have the value `null`\nby adding `?` to its type declaration.\n\n```dart\nint? isNullableInt = null;\n```\n\n#### The `final` keyword\n\n`final` can be used to create a constant.\nA constant _must_ be declared and initialised at the same time\nand cannot be changed once it has been declared.\n\n```dart\nfinal a = 42;\n```\n\n**error**\n```dart\nfinal a;\na = 42;\n```\n\nThe type of the variable/constant can be also used with `final`:\n\n```dart\nfinal int a = 42;\n```\n\nAttempting to reassign a constant created with `final` keyword will produce an error:\n\n**error**\n```dart\nfinal int a = 42;\na = 52; // error as the variable a is already defined\n```\n\n#### The `const` keyword\n\nThe `const` keyword is another way for creating constant value.\nThe difference with `final` is that the variable created with `const`\nmust be initialised at ***compile time***, `const birth  = \"2008/12/26\"`\nwhereas a `final` value must be known at ***runtime***, `final birth  = getBirthFromDB()`. Neither can be changed after it has been initialised.\n\n```dart\nconst int a = 42;\n```\n\n**error**\n```dart\nconst int a = 42;\na = 52; // attempting to assign a new value to a constant.\n```\n\n#### The `dynamic` keyword\n\nThe `dynamic` keyword is used to create a variable that\ncan contain values of different types. It should be used sparingly\notherwise we lose the primary benefit of a statically typed language.\n\n```dart\ndynamic a;\na = 42;\na = 'hello'\n```\n\nBecause the type of the variable can change,\nwe can't write the following:\n\n```dart\ndynamic int a; // https://repl.it/repls/GreenDeadMatch\na = 42;\n```\n\n#### The `late` keyword\nIn Dart 2.12, the `late` keyword modifier was introduced.\nThis keyword is meant to be used solely on two scenarios:\n\n##### Declaring a non-nullable variable that’s initialized after its declaration.\n\nUsing `late` before variables makes sure that variable must be initialized later.\nOtherwise you can encounter a runtime error when the variable is used.\n```dart\nlate String name;\n\nvoid getName(){\n    title = 'Ami';\n    print('Name is $title');\n}\n```\n\n##### Lazily initializing a variable.\n\nThis is handy when a variable might not be needed and,\ninitializing it is costly. \n\nIf we don't use `late`\n\n```dart\nString result = getExpensiveResult();\n```\n\nIn the above code, \nimagine the `result` variable is never used.\nThe `getExpensiveResult()` function is still executed.\n\nIf we do use `late`\n\n```dart\nlate String result = getExpensiveResult(); // Lazily initialized.\n```\n\nIn the above code, since `result` is never used,\n`getExpensiveResult()` is never executed.\nI\n\n\n### `main()` function\n\nThe main function is a top-level function (a function created outside of a class) which is required in all Dart programs.\nIt is the starting point of your program. It usually has the type void.\n\nvoid main() {\n  print('hello');\n}\nThe main function can take a list of string as a parameter.\n\n### Arrow functions\n\nArrow functions is a syntactic sugar expression to create one statement function.\n\n```dart\nString hello() =\u003e 'hello'\n```\n\nis the same as\n\n```dart\nString hello() {\n    return 'hello';\n}\n```\n\nArrow functions can also be used to create anonymous functions:\n\n```dart\nvoid main() {\n    var hello = () =\u003e 'hello';\n    print(a());\n}\n```\n\n### Named parameters\n\nNamed parameters make it easier to understand \nwhich value is assigned to the argumment of a function.\\\n\n**Positional parameters** rely\non the order of the parameters given to the function. \n\n**Named parameters** instead rely\non the name given to the parameter,\nand discard the order.\n\nYou define the parameters inside `{}` \nand when the function is called assign the values\nto the paremeters with ':':\n\n```dart\nString hello({String firstName, String lastName}) {\n  return '$firstName $lastName';\n}\n\nvoid main() {\n    var myName = hello(firstName: 'bob', lastName: 'Smith');\n    var myNameAgain = hello(lastName: 'smith', firstName: 'bob'); // the order of the parameter doesn't matter\n    print(myName);\n}\n```\n\nBy default named parameters are optional:\n\n```dart\nString hello({String firstName, String lastName}) {\n  return '$firstName $lastName';\n}\n\nvoid main() {\n    var myName = hello(firstName: 'bob');\n    print(myName); // print 'bob null'\n}\n```\n\nIf you want a parameter to be mandatory you can anotate it with `@required`.\nYou need first to import the 'meta' package which contains this anotation:\n`import 'package:meta/meta.dart';`\n\nFlutter also contains this anotation in the foundation.dart package:\n`import 'package:flutter/foundation.dart';`\n\nSelect one of these two import depending if your project is a Flutter application or just a Dart program.\n\n## Asynchronous events\n\n`Dart` provides the `Future` class to represent asynchronous events.\nFor example the following `hello` function will return a `String`  in a near future:\n\n```dart\nFuture\u003cString\u003e hello() { // The type parameter of Future is a String, represented by \u003cString\u003e\n    return Future.delayed(Duration(seconds: 2), () =\u003e \"hello\"); // Using the Future.delayed function to create a time gap of 2 seconds\n}\n```\n\nA function with a return type of `Future\u003cT\u003e` (where `T` represents any type)\ncan have _three_ possible return states:\n`Uncompleted`, `Completed ` (_with_) ***success*** and `Completed` (_with_) ***error***\nWhen completed the function will return the type `T`, in our case the `hello` function returns a `String`.\nIf an error occurs then the function will return an `Error`.\n\nTo be able to use the returned value of an asynchronus function we can use the `async` and `await` keywords.\nWe need first to describe the function using an asynchronous function by adding the `async` keyword before the body of the function.\nThen we using the asynchronous function we prefix the call to the function with `await`. This will stop the process of the function\nand wait for the future result. For example we can create a `main` function which will use our `hello` function:\n\n```dart\nvoid main() async {\n    String hi = await hello();\n    print(hi); // print \"hello\" after 2 seconds\n}\n\nFuture\u003cString\u003e hello() { // The type parameter of Future is a String, represented by \u003cString\u003e\n    return Future.delayed(Duration(seconds: 2), () =\u003e \"hello\"); // Use Future.delayed to delay execution by 2 sec.\n}\n```\n\nTo test this code you can copy/paste it and run it on dartpad: https://dartpad.dev/\n\nIf we do not add the `async/await` keywords, we can still call the asynchronous `hello` function,\nhowever the result won't be ready and the `Future` instance will be returned instead of the String:\n\n```dart\nvoid main() {\n    dynamic hi = hello();\n    print(hi); // print \"Instance of _Future\u003cString\u003e\"\n}\n\nFuture\u003cString\u003e hello() { // The type parameter of Future is a String, represented by \u003cString\u003e\n    return Future.delayed(Duration(seconds: 2), () =\u003e \"hello\"); // Using the Future.delayed function to create a time gap of 2 seconds\n}\n```\n\nWe can also use the `then` function which takes a callback function to get the future value:\n\n\n```dart\nvoid main() {\n    hello().then((futureValue) { // futureValue is the retuned value of the hello function\n        print(futureValue); // print after 2 seconds \"hello\"\n    });\n}\n\nFuture\u003cString\u003e hello() { // The type parameter of Future is a String, represented by \u003cString\u003e\n    return Future.delayed(Duration(seconds: 2), () =\u003e \"hello\"); // Using the Future.delayed function to create a time gap of 2 seconds\n}\n```\n\nCompared to `await`, `then` will not stop the process of the function and continue the execution:\n\n```dart\nvoid main() {\n    hello().then((futureValue) { // futureValue is the retuned value of the hello function\n        print(futureValue); // print after 2 seconds \"hello\"\n    });\n    print('printed first'); // This print will be displayed before 'hello'\n}\n\nFuture\u003cString\u003e hello() { // The type parameter of Future is a String, represented by \u003cString\u003e\n    return Future.delayed(Duration(seconds: 2), () =\u003e \"hello\"); // Using the Future.delayed function to create a time gap of 2 seconds\n}\n```\n\n## Object-Oriented Programming in Dart\n\n`Dart` is an Object-Oriented language.#\nObject Orientation is a software development paradigm that follows real-world modelling.\nObject Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods.\n\n- Object\n- State\n- Behavior\n- Identity\n- Class\n- Method\n\n### Constructor\n\nConstructors let you create an instance of a class.\nWhen creating a class, Dart will provide a default constructor for this class.\n\n```dart\nclass Car {\n    String engine;\n}\n\nvoid main() {\n  Car myCar = Car(); //The Car() constructor is provided automatically\n  print(myCar); // print Instance of 'Car'\n}\n```\n\nYou can also create a named constructor with the syntax `ClassName.constructorName`:\n\n```dart\n class Car {\n     String engine;\n\n     Car.withEngine(String engine) {\n         this.engine ='engine $engine';\n     }\n }\n```\n\nDart also provides a syntax sugar for a constructor which assigned instance variable:\n\n```dart\nclass Car {\n    String engine;\n\n    Car(this.engine); // Create a constructor which defined the engine value\n}\n\nvoid main() {\n    Car c = Car('electric');\n    print(c.engine);\n}\n```\n\n### Initializer list\n\nInitializer list are used to assigned values to instance variables:\n\n```dart\nclass Pet {\n    final String name;\n    final int age;\n\n\n    Pet.initialise() : this.name = 'Bob', this.age = 2; // assigned default values to final variables\n\n    String getInfo() {\n        return 'name: $name, age: $age';\n    }\n}\n\nvoid main() {\n    Pet p = Pet.initialise();\n    print(p.getInfo());\n}\n```\n\nInitializer list can also be used to redirect a contstructor of a class to another one:\n\n```dart\nclass Pet {\n    String name;\n\n    Pet(this.name); // create a constructor which set the name variable\n\n    Pet.setName(String name) : this(name); // redirect the setName constructor to the Pet(name) constructor\n}\n\nvoid main() {\n    Pet p = Pet.setName('Bob');\n    print(p.name);\n}\n```\n\n### inheritance\n\nA class can `extends` another class to create a sub class.\nA sub class can only extends one class only.\n\n```dart\nclass Pet {\n    String name;\n\n    Pet() : name = 'Mike';\n}\n\nclass Cat extends Pet {\n    Cat() {\n        name = 'Dave';\n    }\n}\n\nvoid main() {\n  Pet p = Pet();\n  Cat c = Cat();\n  print(p.name); // print Mike \n  print(c.name); // print Dave\n}\n```\n\nIf you want to redefine a method in a sub class, you can use the `@override` annotation:\n\n```dart\n class Pet {\n     String name;\n   \n     Pet(this.name);\n\n     String getName() {\n        return 'the pet name is: $name';\n     }\n }\n\n class Cat extends Pet {\n     Cat(String name) : super(name);\n\n     @override\n     String getName() {\n         return 'the cat name is: $name';\n     }\n }\n\nvoid main() {\n  Cat c = Cat('Bob');\n  print(c.getName()); // print the cat name is: Bob\n}\n```\n\n### abstract class\n\nIf the parent class is created with the `abstract` keyword then only a child class can \ncreate an object instance as abstract class can't be instantiated.\n\n```dart\nabstract class Pet {\n    String name;\n}\n\nclass Cat extends Pet {\n    Cat() {\n        name = 'Dave';\n    }\n}\n\nvoid main() {\n  Pet p = Pet(); // error, Pet is an abstract class\n  Cat c = Cat();\n  print(c.name); // print Dave\n}\n```\n\nUnlike \"normal\" class, an abstract class can contain methods without bodies.\nThe idea is to let the sub class implement the logic of the method:\n\n```dart\nabstract class Pet {\n  void printMessage();\n}\n\nclass Cat extends Pet {\n  @override\n  void printMessage() { // the printMessage implementation is required in subclass\n    print('cat class');\n  }\n}\n\nvoid main() {\n  Cat c = Cat();\n  c.printMessage(); // cat class\n}\n```\n\n\nWhen creating an instance of an inherited class, first the initialiazer list is run (if any) then\nthe default constructor of the parent class and\nfinally the default constructor of the class:\n\n```dart\nclass Pet {\n    String name;\n\n    Pet() : name = 'Dave'{\n        print('Pet name: $name');\n    }\n}\n\nclass Cat extends Pet {\n    Cat() {\n        print('Cat name: $name');\n    }\n}\n\nvoid main() {\n  Cat c = Cat();\n  // The name is set using the initializer list\n  // then the parent constructor is run\n  // then the cat constructor is run\n\n  // print Pet name: Dave\n  // then print Cat name: Dave\n}\n```\n\n### Class interface with `implements`\n\nInstead of using `extends` to inherite a behavior of a class,\nDart provides the `implements` keyword which allows you to use classes as interfaces\nfor another class. This class doesn't inherite any method logic but it will have to define\nthe types and method of the referenced classes.\n\n```dart\nclass PetA {\n    String name;\n}\n\nclass PetB {\n    int age;\n}\n\nclass Cat implements PetA, PetB {\n    @override\n    String name;\n    @override\n    int age;\n  \n    Cat(this.name, this.age);\n}\nvoid main() {\n    Cat c = Cat('Dave', 2);\n    print(c.name);\n    print(c.age);\n}\n```\n\n## Useful tools to use with Flutter\n\nThe `Dart` language is familiar to most developers used to object oriented programming.\nThere are a [few best practices](https://dart.dev/guides/language/effective-dart)\nworth learning to ensure success.\n\nThere are some tools that can make the process of\ndevelopment much easier and intuitive:\n\n\n## Dartanalyzer\n\n[`Dartanalyzer`](https://dart.dev/tools/dartanalyzer) is static analysis tool for `Dart`. \nIt analyses your code for common mistakes and makes suggestions for how to simplify things. \nIt corrects code before we run the application.\u003c/br\u003e\n\nThis is an example of performing static analysis\nover all the `Dart` files under the lib and test directories:\n`dartanalyzer lib test`\n\n\n## Linting\n\nInitially, developers used [pedantic](https://pub.dev/packages/pedantic),\na package that showed how static analysis and analysis options\nmatching those used internally at Google.\n\nHowever, having been discontinued, it's rather common \nto use the [`Official Dart lint rules`](https://pub.dev/packages/lints) \n(or [`flutter_lints`](https://pub.dev/packages/flutter_lints),\nwhich extends it to Flutter) for static code analysis.\n\nIt contains linting of `Dart` code that are used in best practices.\u003c/br\u003e\n\nFor new apps created with `dart create`, the lints\nare enabled by default. In case you want to add these,\nsimply run this at the root of your package:\n\n`dart pub add --dev lints`\n\nCreate a new `analysis_options.yaml` file next to the `pubspec.yaml` file.\n\n`include: package:lints/recommended.yaml`\n\nAnd you should be done!\n\n\n## `Dart` Testing\n\nThe purpose of automated software testing is quality assurance and system reliability.\u003c/br\u003e\nIt gives _assurance_ that the features built in the application conform to the original specification and acceptance criteria.\nSeveral tests can be created to test functionality, usability, performance or security.\u003c/br\u003e\n\n## Types of Tests\n\nThere are several types of software tests.\nIn `Dart` the most commonly used tests are unit, component and end-to-end; usually in that order.\n\n### Unit Tests\n\nUnit tests are test small parts of code, such as a function, a class, or a change made to the layout.\nEvery function must have at least one unit test.\nA function with multiple possible outcomes must have multiple tests; one for each case.\nEach function should be responsible for doing one thing.\nIf your function does multiple things or you use the word \"and\"\nwhen describing what a function does,\nthat's usually a [bad sign](https://en.wikipedia.org/wiki/Code_smell).\nWe use small single responsibility tested functions to assemble a larger application.\nSee: https://en.wikipedia.org/wiki/Single_responsibility_principle\nand https://blog.codinghorror.com/curlys-law-do-one-thing/\n\n### Component Tests\n\nComponents are composed of several smaller functions once all the unit tests for those functions are passing.\nComponent tests test several functions or tasks assembled into a feature at the same time as a whole.\n\n### End-To-End Tests\n\nThe end-to-end tests are used to test entire applications or most of them on real devices, or a browser.\n\n## Useful libraries in Dart\n\nThere are also some libraries that can be useful when talking about Dart:\n\n```package:test```\n\nIt helps us to have a perception of how we have to put the code, it serves to test small codes or big codes.\n\n```package:mockito```\n\n[Mockito](https://pub.dev/packages/mockito) is a mocking library that helps us to mock functionality where we don't want to perform a specific action. We try to _avoid_ using mocks as much as possible because they can inadvertently make our tests more complex with limited benefit.\n\n## Publishing Packages to `pub.dev`\n\nThere are many libraries \nin the Dart ecosystem;\nsee:\n[pub.dev/packages](https://pub.dev/packages)\nAt the time of writing this doc,\nthere are **`30643`** published packages:\n\n\u003cimg width=\"1350\" alt=\"dart pub.dev packages\" src=\"https://user-images.githubusercontent.com/194400/205872136-fbf87baf-e70b-47f2-bfc7-2e693a496dcb.png\"\u003e\n\nThis number grows daily \nand by the time you read this it might be much higher!\n\nIf you want to develop your own package\nand share it with the world,\nyou have to know how to *publish* it.\nLuckily for you, we got you covered!\nCheck the \n[`publishing-packaged.md`](./publishing-packages.md)\nfile for detailed instructions\non how to get started! 🎉\n\n\n## `Dart` VS Javascript:\n\nDart:\n\n- Backed by Google\n- In some instances, `Dart` is up to [twice the speed](https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/dart.html) of JavaScript\n- Quite scalable across projects\n- Like Java\n- Used extensively for the Flutter mobile UI framework\n\nJavascript:\n\n- Can be used on both front-end and back-end\n- Used everywhere!\n- Comes with lots of great and popular frameworks\n- Fast, light-weight and flexible\n- Can’t run a device which doesn’t use JavaScript today\n","funding_links":[],"categories":["Others"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdwyl%2Flearn-dart","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdwyl%2Flearn-dart","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdwyl%2Flearn-dart/lists"}