Dart

I checked out a few of the videos on Flutter.dev and was intrigued as I love acquiring new knowledge. The first problem that I foresaw was Dart , the language used for Flutter. Darn here  was yet another programming language to add to my list , C,C++, C#, JavaScript, and Swift.  So I dove into a couple of tutorials especially the lanquage tour . As a C# and JavaScript developer I was heartened by the similarities to Dart. I brought up the DartPad tool and started to play. This cool tool  reminded me of the Swift Playgrounds as these tools are great learning tools. Note that Dart compiles into Javascript for web apps and there is an Flutter for Web in the works.  The learning curve  is incredibly short so lets look at  few differences from C#. I unashamely ripped off part of text from the Dart Language tour

Everything you can place in a variable is an object, and every object is an instance of a class. Even numbers, functions, and null are objects. All objects inherit from the Object class.  

This is much like JS where everything is an object but of course not  class as there are none. In C# there are references that
store references to their data (objects), while variables of value types directly contain their data .


Numbers:

Dart numbers come in two flavors:

int

Integer values no larger than 64 bits, depending on the platform. On the Dart VM, values can be from -263 to 263 – 1. Dart that’s compiled to JavaScript uses JavaScript numbers, allowing values from -253 to 253 – 1.

double

64-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard.

This is much like JS and of course C# has  lot more such as long,short etc. I like the Dart approach.

Variables

in Dart variables store references as :

var name = ‘John’    //name is inferred to be  a reference to a string

much the same as C# but in C# the var represents a implicitly typed local variable. The Dart var is much like JS but once assigned the type cannot be changed. JS is completely dynamic a feature that I love and hate.

Now if you want the flexibility of JS var use the dynamic keyword:. I have never found a need to use this as I like type checking.

Default value

Uninitialized variables have an initial value of null. Even variables with numeric types are initially null, because numbers—like everything else in Dart—are objects.

int lineCount;
assert(lineCount == null);

Things are much more complicated in C# as one can see here

Final

unlike c# dart has a Final which is used if you never intend to change a variable

Strings

A Dart string is a sequence of UTF-16 code units. You can use either single or double quotes to create a string. 

String test = ‘ffff’ ; or “fff”

C# a string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. Char is used to represent single  UTF-16 code unit. There is no need for this in Dart

Lists and arrays in Dart

Dart arrays are Lists, so look for List in the documentation. A Dart List will compile to a JavaScript array.the word “array” does not appear in the Dart spec.

so if we have in c# int [] marks = new int[5] { 99, 98, 92, 97, 95};

in Dart we have List balance = [99, 98, 92, 97, 95]; 

or List<int>  balance = [99, 98, 92, 97, 95];  

This last statement is big as yes there are Generics

for more on List see Seth ladd Blog

Expressions vs Statements

Dart has both expressions (which have runtime values) and statements (which don’t). For example, the conditional expression condition ? expr1 : expr2 has a value of expr1 or expr2. Compare that to an if-else statement, which has no value. A statement often contains one or more expressions, but an expression can’t directly contain a statement. This will become important with => functions later. this is much same as C# as both are imperative languages for more in C#

Functions

Functions are more like JS then C# Dart is a true object-oriented language, so even functions are objects and have a type, Function. This means that functions can be assigned to variables or passed as arguments to other functions. You can also call an instance of a Dart class as if it were a function. For details, see Callable classes.

Here’s an example of implementing a function and looks like C#

bool isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

Unlike C# the function still works if you omit the types:

isNoble(atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

For functions that contain just one expression, you can use a shorthand syntax:

bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

Note: The => expr syntax is a shorthand for { return expr; }. The => notation is sometimes referred to as arrow syntax in Dart and of course lambda in C#. we must be careful to understand they are not quite the same as => is the same as Expression Lambda in C#. But in Dart Only an expression (NOT A STATEMENT) can appear between the => and the semicolon. e.g no if statements but only conditional expression e.g. => value.isEmpty ? ‘phone number empty’ : null. In C# we can have Statement Lambdas with multiple statements

A function can have two types of parameters: required and optional. The required parameters are listed first, followed by any optional parameters. Optional parameters can be named or positional.

Note: Some APIs — notably Flutter widget constructors — use only named parameters, even for parameters that are mandatory. See the next section for details.

Optional parameters

Optional parameters can be either named or positional, but not both.

Named parameters

When calling a function, in Dart you can specify named parameters using paramNamevalue. For example:

enableFlags(bold: true, hidden: false);

When defining a function, use {param1param2, …} to specify named parameters:

/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold, bool hidden}) {...}

in C# 4 there are named parameters too but do not need the curlys so the definition of a function looks like :

 void enableflags(bool bold,bool hidden){…}

and C# caller looks same as Dart

Positional parameters

Wrapping a set of function parameters in [] marks them as optional positional parameters:

int ExampleMethod(int required, String optionalstr, [int optionalint = 10]
){   return optionalint; }   

in C# Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters

Functions are first-class objects in Dart

This makes it easy  pass a function as a parameter to another function. For example

Now we can do almost the same in c# using delegates which are a reference  but are not objects and not quite as easy but close . I like the Dart and JS approach here.  the C# code might look like:

:

Anonymous functions

in Dart An anonymous function looks similar to a named function— zero or more parameters, separated by commas and optional type annotations, between parentheses.

The code block that follows contains the function’s body:

([[Typeparam1[, …]]) { 
  codeBlock
}; 

in C# pretty much the same as An anonymous function is an “inline” statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

You can use a lambda expression or an anonymous method to create an anonymous function.

we can use a delegate:

TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); }; or as lambda.

TestDelegate testDelC = (x) => { Console.WriteLine(x); };

for more details

so if we have the following Dart code that uses an anonymous function :

var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) { print('${list.indexOf(item)}: $item'); });

in C# we could write something like:

list.foreach(
   i => Console.write(i);
);

Operators

I have found very little differences here as both are C based. Dart even has the is and as operators.

Conditional expressions are same

Dart has two operators that let you concisely evaluate expressions that might otherwise require if-else statements:condition ? expr1 : expr2

If condition is true, evaluates expr1 (and returns its value); otherwise, evaluates and returns the value of expr2.

expr1 ?? expr2

If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2.

Cascade notation (..)

 Dart and Javascript have  Cascades (..) allow you to make a sequence of operations on the same object. In addition to function calls, you can also access fields on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.

Consider the following JS code (we can do much same in Dart):

querySelector('#confirm') // Get an object.
   ..text = 'Confirm' // Use its members.
   ..classes.add('important') 
  ..onClick.listen((e) => window.alert('Confirmed!'));

of course in c# we just break this up in separate statements.

Control flow statements

You can control the flow of your Dart code using any of the following:

  • if and else
  • for loops
  • while and dowhile loops
  • break and continue
  • switch and case
  • assert

These are almost exactly like C#

Classes

Dart is an object-oriented language with classes. Every object is an instance of a class, and unlike C# all classes descend from Object. The majority of your c# experience carries forward here but there are differences.

the new keyword is optional 

there is syntactical sugar for setting instance variables so instead of

 class Point { 

int x, y; 

Point(int x, int y) {

    this.x = x;    this.y = y;  }}

we can write :

class Point { 

int x, y;

Point(this. x, this. y); }

There are named constructors:

class Point {  num x, y; 

Point(this. x, this. y);// Named constructor  Point.origin() {              x=0;             y=0;        }}

}There are named constructors:

class Point {  num x, y; 

Point(this. x, this. y);

// Named constructor

  Point.origin() {              x=0;             y=0;        }}

Initializer list

you can also initialize instance variables before the constructor body runs in Dart. Separate initializers with commas.

// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map<String, num> json)
    : x = json['x'],
      y = json['y'] {
  print('In Point.fromJson(): ($x, $y)');
}

Factory constructors

Use the factory keyword when implementing a constructor that doesn’t always create a new instance of its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype.

have never used this feature and really do not get the point

Extending a class

Use extends to create a subclass, and super to refer to the superclass:

class Television {   void turnOn() {     _illuminateDisplay();     _activateIrSensor();   }   // ··· }
class SmartTelevision extends Television { void turnOn() { super.turnOn(); _bootNetworkInterface(); _initializeMemory(); _upgradeApps(); } // ··· }
same in C# but extends becomes : 
Adding features to a class: mixins Mixins are a way of reusing a class’s code in multiple class hierarchies. To use a mixin, use the with keyword followed by one or more mixin names. The following example shows two classes that use mixins: 
class Musician extends Performer with Musical { // ··· }
class Maestro extends Person with Musical, Aggressive, Demented { Maestro(String maestroName) { name = maestroName; canConduct = true; } }

To implement a mixin, create a class that extends Object and declares no constructors. Unless you want your mixin to be usable as a regular class, use the mixin keyword instead of class. For example:
mixin Musical { bool canPlayPiano = false; bool canCompose = false; bool canConduct = false;
void entertainMe() { if (canPlayPiano) { print('Playing piano'); } else if (canConduct) { print('Waving hands'); } else { print('Humming to self'); } } }

now this feature can be approximated in c# using extensions


Private/Public access modifiersThese attributes do not exist in Dart but If an identifier starts with an underscore (_), it’s private to its library. 

Generics

OMG even these exists and pretty well the same as we can write :

List<String> my = new List<String>();

Dart does provide an additional capability:

 collection literals

List, set, and map literals can be parameterized. Parameterized literals are just like the literals you’ve already seen, except that you add <type>(for lists and sets) or <keyTypevalueType> (for maps) before the opening bracket. Here is example of using typed literals:

var names = <String>['Seth', 'Kathy', 'Lars']; 
var uniqueNames = <String>{'Seth', 'Kathy', 'Lars'};
var pages = <String, String>{ 'index.html': 'Homepage', 'robots.txt': 'Hints for web robots', 'humans.txt': 'We are people, not machines' };

Asynchrony support

Dart libraries are full of functions that return Future or Stream objects. These functions are asynchronous: they return after setting up a possibly time-consuming operation (such as I/O), without waiting for that operation to complete.

The async and await keywords support asynchronous programming, letting you write asynchronous code that looks similar to synchronous code.

Future<UserResponse> signUp(User user) async {
      UserResponse resp = new UserResponse();
      var url = "http://foo.com/api/Account/Register";
     try {
        final response = await http
          .post(url    .....

      our C# code would be much the same except the return type would be something like Task<UserResponse>. 


I will add to this blog from time to time but I think you can see that the learning curve here is gentle as the the 2 languages have so much in common

Leave a reply:

Your email address will not be published.

Site Footer

Sliding Sidebar