<commit_before>---
layout: post
lang: en
title: "Flutter introduction from a Xamarin developer"
image: images/yoga
categories:
  - Flutter
tags:
  - Flutter
  - Dart
  - Xamarin
  - versus
---

Maybe you never heard about me, but I have been a Xamarin developer for four years now, always obsessed in code sharing strategies. I was so exited when I first discovered those tools which allowed me to share a big amount of logic in C# language, you couldn't imagine; and today I feel the same with [Flutter](http://www.flutter.io). In this long post, I will try to share various reflexions after several weeks of experimentation.

##### Disclaimer

> The tools are continuously evolving, so you can read things that are not valid at the time you read it

## The language : Dart

### Seriously ?

I almost never seen any [Dart](https://www.dartlang.org/) mention in many years and  my first thought when I knew that the Flutter team chose this language for the core tools was : 

> Why this language? Their are plenties of already well-known languages, including Kotlin that is currently pushed for Android development. This will slow down user adoption for sure...

Anyway, after a few lines of code I understood: this language is developped internally at Google, and they have a total control on how it should adapt on every platform, and you can feel it. It doesn't have a long history behind it, with various compatibility constraints (like Java/.NET environment). So everything has been designed for what you are using today, and it's really pleasant to use.

### A simple but powerful language

It is very easy to learn Dart syntax if you are familiar with OOP languages like C#, Java, Swift, Kotlin or Javascript. I made a quick selection of language specificities to make you more confident with it.

#### Modules

The strange thing when coming from Java or C# world, is the module oriented architecture (much like Javascript). It is then common to have multiple classes in the same file, and also to declare elements at the module level since module imports can be explicitely named.

#### Statically typed

The language is statically typed, even if it may not be obvious at first glance, because of type inference and dynamics.

```dart
var myVar = this.calculateVar();
final myFinal = const EdgeInsets.all(10.0);

```

Again, type inference is also present in C#, but in Dart you can often omit it from declarations. To be honest, I am not a big fan of it and it can make code readability worse. But the Dart team could change it in the coming versions to make it more strict. 

The `dynamic` keyword looks a lot like the C# one too. 

#### Declaring objects

There are several differences with Java or C#.

First in Dart, interfaces are implicit : every class could be used as an interface with the `implements` keyword. Though, you can declare a class as `abstract` to make it not instanciable.

Moreover, unlike typical languages, there isn't any keyword for defining a method as `private` or `public`. In Dart, you simply prefix your member by `_` for declaring it as private, else it is public. The interesting part is that a private member is visible from the library (aka module), so it's more an `internal` equivalent than private and it is clear that you have to think your software architecture differently around modules.

You can have `static` and readonly fields with `final` keyword.

Syntaxic sugar is also available to make constructor declarations simpler.

```dart
class User {
  final String firstname, lastname;
  String get fullname => "$firstname $lastname";
  User(this.firstname, this.lastname);
  String greet(String who) => 'Hello $who. I am real person.';
}

class Impostor implements User {
  @override
  String greet(String who) => "Hi $who. Ah ah, I'm an impostor!";

  @override
  String get firstname => null;

  @override
  String get fullname => null;

  @override
  String get lastname => null;
}
```

#### Type matching

It is pretty common to test the type of an instance, and Dart makes it easy by simply casting the object for you.

```dart
final result = getResult();
if(result is String) {
	final length = result.length; // result is cast as String
}
else if(result is int) {
	final addition = result + 5; // result is cast as Int
}
```
Again, .NET developers have similar operations with C# 7 (and even more with pattern matching).

#### Named constructors

It is common to have static factory functions to instanciate objects in other languages to make clear of how they were constructed. Dart provides a way to name constructor variants for this purpose.

```dart
class Customer {
	final String name;
	
	Customer(this.name);
	
	Customer.fromMap(Map map) : this.name = map["name"];
}
```

#### Asynchronicity

You also have all the helper functionalities you could expect from a modern language like `Future`/`async`/`await` keywords that greatly simplifies the state management of asynchonous operations.

Here a short example of an HTTP call to a REST api (it should look really familiar to any .NET developer that used `HttpClient`/`Task`/`async`/`await`/`JsonConvert`) :

```dart
/// Gets a list of customers from a distant server.
Future<List<String>> getCustomers() async {
  var httpClient = new HttpClient();
  var uri = Uri.parse('http://company.com/api/customers');
  var request = await httpClient.getUrl(uri);
  var response = await request.close();
  if (response.statusCode == HttpStatus.OK) {
	  var responseBody = await response.transform(UTF8.decoder).join(); // [ "...", "...", ... ]
	  return JSON.decode(responseBody).toList();
  }
  throw("failed to load customers");
}
```

#### Reactive programming

The Dart language has built-in [Stream](https://www.dartlang.org/tutorials/language/streams) APIs that are well fitted for reactive-like programming.

```dart
Future<int> sum() async {
	final Stream<int> stream = this.openStream();
	return await stream.reduce((a,b) => a + b);
}
```<commit_msg>Fixed the Future identified as keyword.<commit_after>---
layout: post
lang: en
title: "Flutter introduction from a Xamarin developer"
image: images/yoga
categories:
  - Flutter
tags:
  - Flutter
  - Dart
  - Xamarin
  - versus
---

Maybe you never heard about me, but I have been a Xamarin developer for four years now, always obsessed in code sharing strategies. I was so exited when I first discovered those tools which allowed me to share a big amount of logic in C# language, you couldn't imagine; and today I feel the same with [Flutter](http://www.flutter.io). In this long post, I will try to share various reflexions after several weeks of experimentation.

##### Disclaimer

> The tools are continuously evolving, so you can read things that are not valid at the time you read it

## The language : Dart

### Seriously ?

I almost never seen any [Dart](https://www.dartlang.org/) mention in many years and  my first thought when I knew that the Flutter team chose this language for the core tools was : 

> Why this language? Their are plenties of already well-known languages, including Kotlin that is currently pushed for Android development. This will slow down user adoption for sure...

Anyway, after a few lines of code I understood: this language is developped internally at Google, and they have a total control on how it should adapt on every platform, and you can feel it. It doesn't have a long history behind it, with various compatibility constraints (like Java/.NET environment). So everything has been designed for what you are using today, and it's really pleasant to use.

### A simple but powerful language

It is very easy to learn Dart syntax if you are familiar with OOP languages like C#, Java, Swift, Kotlin or Javascript. I made a quick selection of language specificities to make you more confident with it.

#### Modules

The strange thing when coming from Java or C# world, is the module oriented architecture (much like Javascript). It is then common to have multiple classes in the same file, and also to declare elements at the module level since module imports can be explicitely named.

#### Statically typed

The language is statically typed, even if it may not be obvious at first glance, because of type inference and dynamics.

```dart
var myVar = this.calculateVar();
final myFinal = const EdgeInsets.all(10.0);

```

Again, type inference is also present in C#, but in Dart you can often omit it from declarations. To be honest, I am not a big fan of it and it can make code readability worse. But the Dart team could change it in the coming versions to make it more strict. 

The `dynamic` keyword looks a lot like the C# one too. 

#### Declaring objects

There are several differences with Java or C#.

First in Dart, interfaces are implicit : every class could be used as an interface with the `implements` keyword. Though, you can declare a class as `abstract` to make it not instanciable.

Moreover, unlike typical languages, there isn't any keyword for defining a method as `private` or `public`. In Dart, you simply prefix your member by `_` for declaring it as private, else it is public. The interesting part is that a private member is visible from the library (aka module), so it's more an `internal` equivalent than private and it is clear that you have to think your software architecture differently around modules.

You can have `static` and readonly fields with `final` keyword.

Syntaxic sugar is also available to make constructor declarations simpler.

```dart
class User {
  final String firstname, lastname;
  String get fullname => "$firstname $lastname";
  User(this.firstname, this.lastname);
  String greet(String who) => 'Hello $who. I am real person.';
}

class Impostor implements User {
  @override
  String greet(String who) => "Hi $who. Ah ah, I'm an impostor!";

  @override
  String get firstname => null;

  @override
  String get fullname => null;

  @override
  String get lastname => null;
}
```

#### Type matching

It is pretty common to test the type of an instance, and Dart makes it easy by simply casting the object for you.

```dart
final result = getResult();
if(result is String) {
	final length = result.length; // result is cast as String
}
else if(result is int) {
	final addition = result + 5; // result is cast as Int
}
```
Again, .NET developers have similar operations with C# 7 (and even more with pattern matching).

#### Named constructors

It is common to have static factory functions to instanciate objects in other languages to make clear of how they were constructed. Dart provides a way to name constructor variants for this purpose.

```dart
class Customer {
	final String name;
	
	Customer(this.name);
	
	Customer.fromMap(Map map) : this.name = map["name"];
}
```

#### Asynchronicity

You also have all the helper functionalities you could expect from a modern language like `async`/`await` keywords and the `Future` type that greatly simplifies the state management of asynchonous operations.

Here a short example of an HTTP call to a REST api (it should look really familiar to any .NET developer that used `HttpClient`/`Task`/`async`/`await`/`JsonConvert`) :

```dart
/// Gets a list of customers from a distant server.
Future<List<String>> getCustomers() async {
  var httpClient = new HttpClient();
  var uri = Uri.parse('http://company.com/api/customers');
  var request = await httpClient.getUrl(uri);
  var response = await request.close();
  if (response.statusCode == HttpStatus.OK) {
	  var responseBody = await response.transform(UTF8.decoder).join(); // [ "...", "...", ... ]
	  return JSON.decode(responseBody).toList();
  }
  throw("failed to load customers");
}
```

#### Reactive programming

The Dart language has built-in [Stream](https://www.dartlang.org/tutorials/language/streams) APIs that are well fitted for reactive-like programming.

```dart
Future<int> sum() async {
	final Stream<int> stream = this.openStream();
	return await stream.reduce((a,b) => a + b);
}
```
{'fraction_non_alphanumeric': 0.08151674601186001, 'fraction_numerical': 0.0010022550739163117, 'mean_word_length': 4.156761412575366, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 29, 'https://': 4, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '399770', 'n_tokens_mistral': 3244, 'n_tokens_neox': 3095, 'n_words': 1699}