Understanding dart syntax - dart

Coming from the java world I have difficulties to understand this code-fragment from the AngularDart pirate badge code lab:
Future _loadData() {
return _http.get('piratenames.json').then((HttpResponse response) {
PirateName.names = response.data['names'];
PirateName.appellations = response.data['appellations'];
});
}
}
From my understanding PirateName is a class and how can the line
PirateName.names = response.data['names'];
write a field of a class without referring to an actual instance?

Dart syntax allows static variables as does Java.
That is a static variable as defined in the source you provided Edit piratebadge.dart and you'll see where it is defined as static.

Related

Multiple Generator calls on Xtext language

We are having a project where we are using Xtext to generate a grammar and create from this language a java output file.
Next to that we want to create also a kind of json output file. which has another extension.
For this we want to split the generators to not mix the java generation and the json generation.
Is there anyway we can call 2 Igenerators when compiling dsl grammar?
Example:
We have 1 language common which generates java file for this we have one IGenerator2 which calls like standard CommonGenerator.
Now we want to create second generator for json file with CommonLineageGenerator.
I have read several threads now were i found the following
component = org.eclipse.xtext.generator.GeneratorComponent {
register = CommonStandaloneSetup{}
outlet = {
path = "${runtimeProject}/src-gen"
}
}
component = org.eclipse.xtext.generator.GeneratorComponent {
register = CommonStandaloneSetup2{}
outlet = {
path = "${runtimeProject}/src-gen"
}
}
Where the StandaloneSetup contains an override of the Igenerator2 bindings
return Guice.createInjector(new CommonRuntimeModule())
return Guice.createInjector(new CommonRuntimeModule() {
override Class<? extends IGenerator2> bindIGenerator2() {
return CommonTracingGenerator;
}
});
We are also using mwe2 , to generate our language configuration.
When executing our compilation it now seems although that he is only taking one Generator. Is there anyway we can accomplish this. A wrapper is also possibility but we really want to avoid of mixing the two types of generations.
kr

Dart extension: don't access members with 'this' unless avoiding shadowing

I'm learning to use the new Dart extension methods.
I'm doing this:
extension StringInsersion on StringBuffer {
void insertCharCodeAtStart(int codeUnit) {
final end = this.toString();
this.clear();
this.writeCharCode(codeUnit);
this.write(end);
}
int codeUnitAt(int index) {
return this.toString().codeUnitAt(index);
}
}
So that I can do something like this:
myStringBuffer.insertCharCodeAtStart(0x0020);
int value = myStringBuffer.codeUnitAt(2);
However, I get the following lint warning:
Don't access members with this unless avoiding shadowing.
Should I be doing something different?
The warning you received means the following:
There is no need to reference the current instance using keyword this. Everything will work without reference to the current instance because the static extension method itself acts as an instance method of extensible type.
Simply put, just remove the reference to the current instance from your code.
From this:
final end = this.toString();
To this:
final end = toString();
It's a style thing, based on Dart's guide. There are examples in https://dart-lang.github.io/linter/lints/unnecessary_this.html.
You can find more about style in https://dart.dev/guides/language/effective-dart/style.
I turn off this rule globally by changing "analysis_options.yaml"
include: package:flutter_lints/flutter.yaml
linter:
rules:
unnecessary_this: false

Variable declaration in Dart

I'm just beginning to learn Dart and Flutter and I was wondering if there is any difference in the following declarations?
final List<WordPair> _suggestions = <WordPair>[];
and
final _suggestions = <WordPair>[];
They both seem to exhibit the same behaviour but I'm wondering if there is some underlying difference?
I prefer the first declaration as I'm coming from a C/C++ back ground
There's no difference between them at all.
The second syntax is here only to avoid pointless repetition.
Usually you should prefer the shorthand in Dart. According to the DO/DON'T of dart, there are some conditions in which you'll want to use the full syntax though.
final List<Foo> globalVariable = <Foo>[];
void func() {
final localVariable = <Foo>[]
}

Laravel AuthServiceProvider code explanation

I'm starting to user Gate in Laravel 5.1, and I got this code from some where in the internet.
<?php
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
/**
* NOTE!!
* First time migration will fails, because permissions table doesn't exists.
*/
foreach($this->getPermissions() as $permission) {
$gate->define($permission->path, function($user) use ($permission) {
return $user->hasRole($permission->roles);
});
}
}
My question is, what is function($user) use ($permission) { in $gate->define($permission->path, function($user) use ($permission) { ??? Why is there use after function()?
If there're some references, I'd love to know/ read it.
It has been described in document of PHP.
Please refer to the example 3 of http://php.net/manual/en/functions.anonymous.php.
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
Your case is
$user->hasRole($permission->roles)
is necessary in order to use the variable of $permission.

Conditional imports / code for Dart packages

Is there any way to conditionally import libraries / code based on environment flags or target platforms in Dart? I'm trying to switch out between dart:io's ZLibDecoder / ZLibEncoder classes and zlib.js based on the target platform.
There is an article that describes how to create a unified interface, but I'm unable to visualize that technique not creating duplicate code and redundant tests to test that duplicate code. game_loop employs this technique, but uses separate classes (GameLoopHtml and GameLoopIsolate) that don't seem to share anything.
My code looks a bit like this:
class Parser {
Layer parse(String data) {
List<int> rawBytes = /* ... */;
/* stuff you don't care about */
return new Layer(_inflateBytes(rawBytes));
}
String _inflateBytes(List<int> bytes) {
// Uses ZLibEncoder on dartvm, zlib.js in browser
}
}
I'd like to avoid duplicating code by having two separate classes -- ParserHtml and ParserServer -- that implement everything identically except for _inflateBytes.
EDIT: concrete example here: https://github.com/radicaled/citadel/blob/master/lib/tilemap/parser.dart. It's a TMX (Tile Map XML) parser.
You could use mirrors (reflection) to solve this problem. The pub package path is using reflection to access dart:io on the standalone VM or dart:html in the browser.
The source is located here. The good thing is, that they use #MirrorsUsed, so only the required classes are included for the mirrors api. In my opinion the code is documented very good, it should be easy to adopt the solution for your code.
Start at the getters _io and _html (stating at line 72), they show that you can load a library without that they are available on your type of the VM. Loading just returns false if the library it isn't available.
/// If we're running in the server-side Dart VM, this will return a
/// [LibraryMirror] that gives access to the `dart:io` library.
///
/// If `dart:io` is not available, this returns null.
LibraryMirror get _io => currentMirrorSystem().libraries[Uri.parse('dart:io')];
// TODO(nweiz): when issue 6490 or 6943 are fixed, make this work under dart2js.
/// If we're running in Dartium, this will return a [LibraryMirror] that gives
/// access to the `dart:html` library.
///
/// If `dart:html` is not available, this returns null.
LibraryMirror get _html =>
currentMirrorSystem().libraries[Uri.parse('dart:html')];
Later you can use mirrors to invoke methods or getters. See the getter current (starting at line 86) for an example implementation.
/// Gets the path to the current working directory.
///
/// In the browser, this means the current URL. When using dart2js, this
/// currently returns `.` due to technical constraints. In the future, it will
/// return the current URL.
String get current {
if (_io != null) {
return _io.classes[#Directory].getField(#current).reflectee.path;
} else if (_html != null) {
return _html.getField(#window).reflectee.location.href;
} else {
return '.';
}
}
As you see in the comments, this only works in the Dart VM at the moment. After issue 6490 is solved, it should work in Dart2Js, too. This may means that this solution isn't applicable for you at the moment, but would be a solution later.
The issue 6943 could also be helpful, but describes another solution that is not implemented yet.
Conditional imports are possible based on the presence of dart:html or dart:io, see for example the import statements of resource_loader.dart in package:resource.
I'm not yet sure how to do an import conditional on being on the Flutter platform.

Resources