Dart Quickstart

By pjain      Published April 25, 2020, 1:14 a.m. in blog Programming   

Part of Dart Series

Dart Quickstart


Variables, inferred static, Dynamic and

OOP* Dart infers types in context. Variables initialized as null. var x; // if no type - Dart assumes dynamic

  • final is like var, except they can only be initialized once (can be done at runtime) but not reassigned.

  • The ‘dynamic’ keyword declares a variable of the type ‘dynamic’ with optional typing - eg as return of funciton

    dynamic sumFn(int a, int b) { return a+b; }

  • const - is determined at compile time ONLY eg class constructor or initialization. Differ from final

  • Type is inferred on init, can change type by reassigning to another

  • static modifier - are available throughout class instances.

  • Prefixing an identifier with an underscore enforces privacy in scope eg class or function scope.

Types 101

  • int Integers (no decimals).
  • double Decimal number (double precision).
  • bool Boolean true or false.
int x = 5; // if try x= "abc" - will give compile error
String s = "abc";
double - floating point, decimals
num - integer or floating point
bool - true, false
List [1,2,3]
Map {"x":1,"y":2}
  • Types are strictly enforced once set.
int x = 5; print(x/2); // error since division expects double types
double x=5; print(x/2); //error since types DONT convert error x=5
double x=5.0; print(x/2); // ok now
        x = 5; print(x ~/ 2); // ~/ is integer division - throw away fractional part
  • Dynamically set - var can handle any type like JS dynamic x = 5;
void main() {
  var x=5;
  print("Hello, World!x="+x.toString());
  • Note - dart has block level { } scoping.

Operators, assign

* / ~/ % +  -   order of precedence
++ --
+ concat for strings

x += 5; x -= 5; x *= 5;

Strings, Templates

  • String Immutable string.
  • StringBuffer Mutable string.
  • RegExp Regular expressions.

  • Strings and escape \n \t \r

       "Adjacent string1" "and string2 auto-concatenated"
       "String with 'embedded string' is ok. Escape isn\'t contractions. \"esc-quote "
    raw strings - r"This is a raw $string"; //don't interpolate this
    file paths double escape \\ - "Path is c:\\bin\\filename.txt";
  • Templated substitution of variables - $var, expressions String name = "Pradeep"; print("Hello, $name"); // escape \$ print("${16 + 4}"); // expression

  • Strings can be addressed like lists of characters - start with first position. list[0] list.length

  • String functions, manipulation

String s2="Dart"; s2.startsWith("Da"); //true
    s2.endsWith("rt."); //true
    s2.indexOf("a"); // 1 - note test string can be a string too, -1 if not found 
    s2.contains("t"); //true
String word = "Anna"; List<String> letters = word.split(''); //list of letters
name.padLeft(12), padRight(n,"0"); // ensure at least n chars long, padded by spaces 
compareStrings(name2, name3, caseSensitive: true));
String name = "philip";
    print(name.substring(2));       // result: "ilip"
    print(name.substring(2, 4));    // result: "il"
    name.replaceAll("lip", "Duck")); //phiDuck


  • DateTime A point in time.
  • Duration A span of time.

System types

  • Uri Uniform Resource Identifier
  • Error Error information

Logic, Control flow

    ops ! == != &gt; &lt; &gt;= &lt;=
num temp = 40;
num cold = 60;
if (temp < cold) {
    print("It is cold");
} else {
    print("It is warm");

switch(lang) {
case "en": print("English"); break;
default: print("Other"); 
while (i <10) { .. ++i; }
do { ... ++i; } while (i <10)
for (int i = 0; i < 10; i++) {   print(i);  }
  • Can compare strings with ==

Functions, Null safety and Functional Programming in Dart


  • fn names any valid identifier letter or _, followed by alpha-num-Underscore.
  • Dart fn names are lower camel case (except first letter)

    void greetMe(String name) { print("Hello, $name");}}

  • Positional optional parms - indicated in [ .. ] in declaration

    void myFunction([String param1, int param2, bool param3]) myFunction("Bob", 54, true); myFunction("Bob", 54); myFunction("Bob"); myFunction(); myFunction(null, 54); // position order must be maintained

  • Named parameters, default assignment - now position can be any if named

    void myFunction([String name = "Jim", int age = 30, bool retired = false]) myFunction( age=54); // position order must be maintained

  • Mixed optional parms

    void myFunction(String name, int age, [bool retired = false])

Named optional parameters allow arguments to be passed in any order. They are designated by curly braces instead of square brackets:

void setFlags({bool bold=true, bool hidden=false})
    setFlags(bold:true, hidden:false);

Optional parameters, even named ones, must come at the end of the list if there are also required parameters in a function's signature:

void myFunction(String name, int age, {bool retired = false})

Note: In Dart, named function parameters are always optional. You cannot create a named, required parameter.

  • Return types and arrow functions brevity

    int sum(int a, int b) { return a+b;} int sum(int a, int b) => a+b;

Annotations in functions

  • @required

  • By default, named parameters are optional.

  • However in Flutter, widget constructors — use only named parameters, even for parameters that are mandatory, this enforces greater readability. Also in flutter, there can be MANY parameters getting order right is hard. In the IDEs, the name parameters can be specified as auto-suggest regardless of order - making it easier to assemble its declarative style.

Although named parameters are a kind of optional parameter, you can annotate them with @required to indicate that the parameter is mandatory — that users must provide a value for the parameter. To use the @required annotation, depend on the meta package and import package:meta/meta.dart.

Null safety in Dart Expressions

As common in functional languages today, Dart supports null aware operations for safety. Most errors of null being handled incorrectly will be

  • expression1 ?? expression2 - evaluates to expression1 if this is not null, otherwise it evaluates to expression2

  • x ??= expression - assigns x to expression only if x is null

  • x?.p - evaluates to x.p if x is not null, otherwise to null

    var x = null; print (x ?? "Default text"); x ??= "Hello"; print(x?.toString());


XFR --- DevOps

pubspec.yaml 101

A simple but complete pubspec looks something like the following:

name: newtify
version: 1.2.3
description: &gt;-
  Have you been turned into a newt?  Would you like to be?
  This package can help. It has all of the
  newt-transmogrification functionality you have been looking
homepage: https://example-pet-store.com/newtify
documentation: https://example-pet-store.com/newtify/docs
  sdk: '&gt;=2.0.0 &lt;3.0.0'
  efts: ^2.0.4
  transmogrify: ^0.4.0
  test: '&gt;=0.6.0 &lt;0.12.0'


  • Every app and package needs a name. It’s how other packages refer to yours, and how it appears to the world, should you publish it. The name should be all lowercase, with underscores to separate words, just_like_this. Use only basic Latin letters and Arabic digits: [a-z0-9_]. Also, make sure the name is a valid Dart identifier—that it doesn’t start with digits and isn’t a reserved word. Try to pick a name that is clear, terse, and not already in use.

If you are making a package, a quick search of packages on the pub.dev site to make sure that nothing else is using your name is recommended.


Every package has a version. A version number is required to host your package on the pub.dev site

A version can be omitted for local-only packages. If you omit it, your package is implicitly versioned 0.0.0.

Semantic versioning

A version number is three numbers separated by dots, like 0.2.43.

Semantic version numbers are always in this format: major.minor.patch. patch - for bugfixes minor - for new features major - a new release, with likely. broken backwards-compatibility and has a completely new user experience.

build - It can also optionally have a build ( +1, +2, +hotfix.oopsie) or prerelease (-dev.4, -alpha.12, -beta.7, -rc.5) suffix.
  • You are encouraged to use a major version, with 0.0 so you won't upgrades to this version sneaking in breaking changes, until you explicitly increment the major number in the pubspec.yaml file.

    • Do this only on reading the change log.
  • A ^ caret before the version number? Based on semantic versioning, this allows the dependency to automatically update to the latest version as long as that version does not contain breaking changes to whatever version number you specified.

  • = ver, <= ver

  • any keyword - it's better not to do this, though, since it would allow automatic updates with changes that could break your app.


  • In pubspec.yaml you declare dependencies as such

    dependencies: shared-preferences:^3.0.0

Style Guide and Tips

  • Dart uses 2-character space indentation by convention.

  • Classes: Avoid new for class instantiation. If the variable value does not change, it is preferable to use final instead of var, to allow compiler to check more. var phil= User("123","Phillip","Developer");

  • In constructors use the data 1-line style of arguments for cleaner User(this.id, this.userId, this.subject);

  • Use fat arrow style to simplify functions String toString() => 'User: $subject';

  • In Flutter, widget constructors — use only named parameters, even for parameters that are mandatory, this enforces greater readability. Also in flutter, there can be MANY parameters getting order right is hard. In the IDEs, the name parameters can be specified as auto-suggest regardless of order - making it easier to assemble its declarative style.

. Packaging Dart to snapshot bundles for production

  • If you are used to simple scripts, are you tired of creating pubspec.yaml and all the assorted files to get an "environment"? Well to bundle an application Dart can create "snapshots" which bundles all files in your project into an executable binary file.

Step1. Create a snapshot after developing, doing pub get, building it and testing it. $ dart --snapshot=

Step2. Run the created snapshot - of course all you need is a Dart VM compatible with all dependencies of your snapshot. $ dart

Documentation Comments

  • If you embed documentation comments eg in your classes and methods, then generating Dartdoc can easily be done by using the dartdoc tool distributed with the SDK.

    /// Documentation comments /// These can reference method types or variables using [square-brackets]


There are no comments yet

Add new comment

Similar posts

List++ Advanced Application Features

Interview Questions in Flutter

NAV: URL Launcher, Deep Links

NAV: Navigation Drawers