Dartosphere Aggregate

16 May 2017 | Filip Hráček

What to expect at Google I/O 2017

Google I/O is happening in Mountain View this week. Here’s what you shouldn't miss if you're coming, or if you're following I/O from home.

Figure 1: One of the Flutter apps that will be live-coded on stage. You will also be able to build it in one of the codelabs.

  • Session: Prototyping to Production: Bridging the Gap with a Common Tool by Fiona Yeung and David Yang
    • Friday, 8:30am PDT
    • Design and engineering collaboration is difficult but vital for iterative user-centered product development. Join us (a designer and UI developer) as we use the Flutter UI framework to evolve a UI concept from prototype to production code. You'll leave this talk with a deeper understanding of how to bridge the gap between designers and UI developers through a prototyping-centric workflow, and why using a single framework between designers and developers helps your team work more efficiently.
  • Session: Single Codebase, Two Apps with Flutter and Firebase by Emily Shack and Emily Fortuna
    • Friday, 10:30am PDT
    • Create an app for both iOS and Android, without building it twice! In this presentation, you'll watch how a single developer, live on stage, uses Flutter and Firebase to build two real native apps from a single codebase. This is real! Along the way you'll learn how to build beautiful cross-platform UIs with Flutter, how you can paint your app to life with Flutter's sub-second hot reload dev experience, and how to use the Firebase SDK with Flutter.
  • 5 codelabs
    • Intro to Dart for Java Developers (20 minutes)
    • Write a Material Design AngularDart Web App (20 minutes)
    • Build an AngularDart & Firebase Web App (25 minutes)
    • Building Beautiful UIs with Flutter (60 minutes)
    • Firebase for Flutter (70 minutes)
  • 2 office hours
    • Flutter team: Wednesday, 4pm—5pm PDT
    • Dart and AngularDart teams: Friday, 10:30am—11:30am PDT
Both talks will be live-streamed (and later on YouTube), and all 5 codelabs will be available online.


Figure 2: Another app that you will be able to build via a codelab. This one is built with AngularDart.

If you want to talk to the team and can’t make it to I/O, feel free to reach out to @dart_lang, @flutterio, or @angulardart on Twitter, Dart / AngularDart / Flutter on Gitter, flutter-dev@ and misc@dartlang on Google Groups, +Dartisans on G+, /r/dartlang or Reddit, or use any of the other channels to reach us.

12 May 2017 | Matan Lurey

Wow! I’d love to talk to you more about this!

Wow! I’d love to talk to you more about this!

03 May 2017 | - Source

Moving To AngularDart 3

Angular Dart 3 final was released and NP8080 (simple web based text editor) has been built with the latest version. It has been a fun little project and I have found myself using it daily as a scratchpad.

Not a massive amount to report - Angular very stable since the Betas. Certainly feeling a bit more Dart-y. The most disruptive change was the deprecation of EventEmitter but as this was a thin wrapper around a standard Dart Stream it wasn't much of a loss though I had 20 occurrences to update!

The code is straightforward as:


final StreamController onShowDialogChange = new StreamController();
...
@Output()
Stream get showDialogChange => onShowDialogChange.stream;
...
void closeTheDialog() {
showDialog = false;
onShowDialogChange.add(showDialog);
}

Of course, another option is to copy the EventEmitter class into your own project. Interesting to see AngularDart using core Dart classes, perhaps the start of a larger divergence of the two codebases.

Looking back to the first build of NP8080, the output JS was 300k(ish). The current build is around 200k JS which is great improvement considering the increase of application code over that time. When you consider a basic Dart web app is around 110k, it is even more impressive to have Angular framework squeezed into <90k.

Please raise an issue if you have a feature request. PRs welcome too!

03 May 2017 | Filip Hráček

AngularDart 3.0: Easy upgrade, better performance

AngularDart 3.0 is now available. It brings better performance and smaller generated code, while also making you more productive.


Version 3.0 is an evolution: although it has some breaking changes (detailed below), it is a smooth upgrade due to minimal public API adjustments. Most of the progress is under the hood—in code quality, stability, generated code size, performance, and developer experience.

Code quality:
  • 2731 instances of making the framework code more type safe (using sound Dart).
  • The AngularDart framework code size is down by 12%.
  • Many additional style updates to the codebase:
    • Changed to use idiomatic <T> for generic methods.
    • Removed NgZoneImpl, all the code exists in NgZone now.
Stability:
  • Many CSS encapsulation fixes due to update with csslib package.
  • Fixed bugs with IE11.


Performance:
  • For the Mail sample app, we see 30% faster time-to-interactive (currently 3812 ms on a simulated 3G connection, measured via Lighthouse).
  • Our large app benchmark shows 2x faster render times of very deep view hierarchies (65ms versus 128ms in October).
  • For AngularDart Components, we see major improvements in performance. For example, the <material-button> component gets initialized 1.5x faster (0.5ms versus 0.7ms in October).


Generated code size:
  • For a small app (GWT Mail sample app), we see
    • 3% reduction since October (2.0)
    • 24% reduction since August (when AngularDart went all Dart)
  • For large apps, we see
    • 13% reduction since October
    • 29% reduction since August


Developer experience:
  • Simplified API
    • Simpler onPush change detection using ComponentState and setState.
    • Only one load method (instead of loadAsRoot, loadAsRootIntoNode).
    • Got rid of TitleService, use idomatic document.title instead.
    • Removed viewBindings (use viewProviders).
    • ngSwitchCase replaces the soft deprecated ngSwitchWhen.
    • XHR is deprecated.
    • EventEmitter is deprecated: use the idiomatic Stream and StreamController instead.
    • Removed IterableDifferFactory.
    • A name parameter is now required for all @Pipe(...) definitions: @Pipe(name: 'uppercase') is replaced by @Pipe('uppercase').
    • null is no longer propagated as an initial change value. Fields must start with a non-null value.
    • Removed NgPlural; use the much more dart-y package:intl instead.
  • Catching bugs earlier
    • selector is now a @required property.
    • ngIf throws if the bound value changes during change detection.
    • In generated .template.dart change detected primitives are typed.
  • Testing
    • package:angular_test with improved NgTestBed.
  • Dev mode tweaks
    • New isDebugMode function.
    • Warning when Dartium is run without checked mode.
    • By default, the ExceptionHandler is a BrowserExceptionHandler which prints to console. You can override it if you don't want this behavior (for example, when releasing to production).
You can find more information in the changelog.

AngularDart 3.0 is production ready, and already used at Google by very large apps like AdWords and AdSense. Upgrade today to make your apps smaller, faster, and more reliable!
01 May 2017 | Matan Lurey

Building a reactive FPS Counter in Dart

As an example of how to build FRP (functional-reactive program[s]) in Dart, I decided to try building an FPS counter — that is, an utility to determine what the frame rate of a running application is.

The end result after building package:fps.

I decided I’d like to have a few goals:

  1. The library, hereby package:fps, should be platform agnostic. That is, I didn’t want to require the use of the browser (requestAnimationFrame) — it should work also in the standalone command-line VM and Flutter.
  2. I wanted it to be extensible — it should be relatively trivial to get the average FPS over a duration of time so the number doesn’t spike back and forth while running.
  3. I wanted to be able to specify a target FPS (say 60), and be able to dynamically change that target if it’s clear the application won’t be able to perform.

Here’s what I wanted my API to look like:

Determining frames-per-second means I want to check, at sporadic moments in my application, how long it’s been since I last was able to check. Assume the following:

  • Rendering is normally measured in seconds, or how many frames fit
  • 1000 milliseconds (ms) is one second
  • Time it takes to render a frame is the difference between two timestamps
  • We can start with emitting a timestamp every “frame”
In Dart, which is single-threaded and based on an event loop, we’ll assume that if we can get control of the event loop at least once every <duration> (idle time) that all previous work was effectively the frame.

I tried implementing it rather naively — I created a new StreamController, and used Future.delayed (which delegates to a Timer on all platforms) to inform when the next frame is:

Note: This is not always accurate — on web specifically we can do this much better with window.animationFrame, but again, I wanted something that would run cross-platform out of the box.

OK, so instead of adding the timestamp, I need to calculate and output the frames per second. I could have done this inline, but instead to make it yet-more-extensible I’ve implemented it via a simple StreamTransformer, which is code I can use on-top of any Stream via transform:

I now get output something like this:

60
60
60
60
60
60
60
60
60

Looks good! I’ve included the source code and an example repo on github.

28 Apr 2017 | Matan Lurey

Writing ridiculously reusable Dart code

One of the most common questions I get for Dart, even within Google, is “how do I make my code more reusable?”. We work on large projects like AdWords, AdSense, and Google’s internal CRM, Greentea — which are all written in Dart.

Reusable bags are sort of like reusable code, right?

I was working with an engineer who was iterating on a new API for the AngularDart router, where we are modeling route changes as immutable state changes:

A question was asked while developing this, though:

A [large] customer says that the default behavior of stripping the query parameters as you navigate from a route to another route was not desired — they’d like to keep all query parameters.

As you can see if you try the demo on DartPad, we print the following:

Route {/ {referredId: 1234}}
Route {/contact {}}

Let’s imagine how we’d implement that — a simple way would be to create a new Route object and copy the previous Route’s query field — or we can even merge it using the Map#addAll API:

Now, if we look at our console, we’ll see:

Route {/ {referredId: 1234}}
Route {/contact {referredId: 1234}}

Now we’ve run into a software engineering conundrum — will all of our users need this functionality? If we provide too little flexibility, teams will fork our code or choose another product. On the other hand, providing too much flexibility and we’ll have built a monolith of code for a simple task.

A naive but not incorrect approach would be to add a flag:

class Router {
final bool persistQueryParameters;
Router({this.persistQueryParameters: false});
}

OK, what’s the problem here? Now you’ve added to your public API, and if the team comes back and says “well, we’d like to persist most query parameters, but not these” you’ll have to change your API or introduce a new flag.

What if instead we injected a function that lets users customize how state changes occur? Let’s try it:

— — Router 1 — —
Route {/ {referredId: 1234}}
Route {/contact {}}
— — Router 2 — —
Route {/ {referredId: 1234}}
Route {/contact {referredId: 1234}}

We’ve given a little bit of flexibility — teams can now define a transformation function that lets them define how they will transition from a previous routing state to a new one — without hard-coding the transformation a specific team wanted.

Do you have your own strategies for writing ridiculously reusable Dart code?

28 Apr 2017 | - Source

Forest Fire - Now With Mountains and Lochs


The forest fire cellular automata was a lot of fun to work on and watch. It has now been updated thanks to a welcome pull request which adds a Speed slider to the UI.

I extended it further to add some simple procedurally generated mountains and lochs (lakes). One challenge here was to keep the time down (it takes a lot of recursion). A quick way to get some speed was to reduce the resolution so each cell is 3 pixels square rather than 1.

The interface isn't as phone friendly as it was but is still usable and runs fine and at a decent speed. This thing will happily keep a core of your CPU burning so be sure to close the tab if you are on low battery!

Thinking ahead I would like to make the mountains less round and add an isometric view. Feel free to beat me to it with a pull request. Enjoy!


28 Apr 2017 | Matan Lurey

As far as I know it’s still maintained — though the author(s) are currently working on the…

As far as I know it’s still maintained — though the author(s) are currently working on the DartDevCompiler and addressing bugs might not have been a huge priority.

27 Apr 2017 | Matan Lurey

Possibilities for function overloading in compile-to-JS languages

We’re constantly talking on the Dart team about how to improve the language (like non-nullable types), and one of the features that has come up informally a few times is function overloading:

In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

In short, this means you can write code like this (here’s a Java example):

A quick note: This is not an official stance of either Dart or Google, and also is not meant to be seen as a negative portrayal of TypeScript, but rather just a comparison of various benefits (and deficiencies) of both languages — for example TypeScript supports union types today and Dart does not.

We can’t do this (yet) in Dart, (or JavaScript, or TypeScript) but you can do:

Of course, this isn’t very ergonomic. We could also omit the type definition entirely, and rely on a runtime check (in Dart) or use a union type (in TypeScript):

Note that in both cases I needed to do additional runtime type-checks to know how to dispatch something to the appropriate code block. I didn’t have to do that in Java.

You might want to ask — what’s wrong with that? Well, nothing is wrong — but certainly you can see problems with both implementations, at least compared with Java and other languages:

  1. In both TypeScript and Dart there are no language-level runtime checks — you have to manually assert that an unexpected type was provided. This has to be maintained as you change the type hierarchy.
  2. In both TypeScript and Dart there is runtime performance overhead — imagine calling consume in a tight-loop hundreds or thousands of time — the compiler.
  3. In TypeScript there is code size overhead — even if you only drink water, and never eat food you’ll still compile and ship the error case and water case to production (this isn’t the case in Dart, see below).
  4. In Dart, there are no static checks when you provide incorrect types. The type is implicitly dynamic (any in TypeScript), which is not the experience most users are used to with strongly-typed Dart APIs.
  5. In TypeScript, static checks are limited to structural, not nominal, types. Which means this is totally legal, and will not produce any static errors:

Tree-shaking partially to the rescue

As noted above, Dart does not have method overloads — yet — but does have pretty powerful tree-shaking. For example, assume the following (now familiar) Dart program:

Can you guess what JavaScript code this compiles to?

That’s right — dart2js has optimized it down to a single print statement. You can learn more about the advanced optimizations dart2js does in this Dart developer summit talk from a past year:

OK, but what about overloading?

Dart, unlike TypeScript, uses a nominal type system, not a structural type system. It’s possible with our new sound type system to prove what the incoming type of something is, and we could statically dispatch it. Imagine this compiled JavaScript (not yet supported):

If this is something you’d like to see in Dart please feel free to comment here or on GitHub so we can help prioritize. I hope you enjoyed this short blog!