I re-read documentation several times, and I am not getting it. What is the difference between these two? Is it only that with dynamic you don't have to define "bindable" attributes? If so, why would one not just use dynamic always. What are the use cases for one over the other? I am just confused about this and would like somebody if possible to clarify this.
Dynamic Options Binding are only available for custom-attributes, not custom-elements. They are useful when you do not know the name of all the possible properties or when there are too many properties and you are a lazy person like me.
So, instead of declaring several bindable properties
export class MyCustomAttribute {
#bindable prop1;
prop1Changed(newValue, oldValue) { }
#bindable prop2;
prop2Changed(newValue, oldValue) { }
#bindable prop3;
prop3Changed(newValue, oldValue) { }
}
you can decorate de class with #dynamicOptions and use a generic method to detect which property has been set
export class MyCustomAttribute {
propertyChanged(name, newValue, oldValue){
switch(name){
case 'prop1':
//do something
break;
case 'prop2':
//do something
break;
case 'prop3':
//do something
break;
default:
//do something
break;
}
}
}
Why not use #dynamicOptions all the time? Because you would be doing unnecessary conditions most of the time, which is not cool :)
Hope this helps!
Related
I have a function that returns either an error message (String) or a Firestore DocumentReference. I was planning to use a class containing both and testing if the error message is non-null to detect an error and if not then the reference is valid. I thought that was far too verbose however, and then thought it may be neater to return a var. Returning a var is not allowed however. Therefore I return a dynamic and test if result is String to detect an error.
IE.
dynamic varResult = insertDoc(_sCollection,
dataRec.toJson());
if (varResult is String) {
Then after checking for compliance, I read the following from one of the gurus:
"It is bad style to explicitly mark a function as returning Dynamic (or var, or Any or whatever you choose to call it). It is very rare that you need to be aware of it (only when instantiating a generic with multiple type arguments where some are known and some are not)."
I'm quite happy using dynamic for the return value if that is appropriate, but generally I try to comply with best practice. I am also very aware of bloated software and I go to extremes to avoid it. That is why I didn't want to use a Class for the return value.
What is the best way to handle the above situation where the return type could be a String or alternatively some other object, in this case a Firestore DocumentReference (emphasis on very compact code)?
One option would be to create an abstract state class. Something like this:
abstract class DocumentInsertionState {
const DocumentInsertionState();
}
class DocumentInsertionError extends DocumentInsertionState {
final String message;
const DocumentInsertionError(this.message);
}
class DocumentInsertionSuccess<T> extends DocumentInsertionState {
final T object;
const DocumentInsertionSuccess(this.object);
}
class Test {
void doSomething() {
final state = insertDoc();
if (state is DocumentInsertionError) {
}
}
DocumentInsertionState insertDoc() {
try {
return DocumentInsertionSuccess("It worked");
} catch (e) {
return DocumentInsertionError(e.toString());
}
}
}
Full example here: https://github.com/ReactiveX/rxdart/tree/master/example/flutter/github_search
Recently I've been delving into Flutter's ecosystem and Dart has proven itself a neat and simple language.
Currently, I am looking for a best practice to run methods if an optional variable is not null.
In other words, I am looking for something in Dart that is like Kotlin's let operator :
variable?.let {
doStuff();
doABitMoreStuff();
logStuff();
}
Anyone got any ideas or best practices around this?
I've looked into Dart's documentation and have found nothing that would fit my requirements.
King regards,
With the new Dart extension functions, we can define:
extension ObjectExt<T> on T {
R let<R>(R Function(T that) op) => op(this);
}
This will allow to write x.let(f) instead of f(x).
Dart's equivalent would be a null-aware cascade operator:
The Dart approach would be a to use a null-aware cascade:
SomeType? variable = ...
variable
?..doStuff()
..doABitMoreStuff()
..logStuff();
The null-aware cascade works like the normal cascade, except that if the receiver value is null, it does nothing.
You could make your own using a static function though:
typedef T LetCallback<T>(T value);
T let<T>(T value, LetCallback<T> cb) {
if (value != null) {
return cb(value);
}
}
Then used like that:
let<MyClass>(foo, (it) {
})
We can do it with Dart 2.6 or later.
extension ScopeFunctionsForObject<T extends Object> on T {
ReturnType let<ReturnType>(ReturnType operation_for(T self)) {
return operation_for(this);
}
}
usage: https://github.com/YusukeIwaki/dart-kotlin_flavor#let
The difference between x?.let{ } and if (x != null) { } in Kotlin is that the former promotes x to be non-nullable. Since Kotlin has non-nullable types, it prevents you from needing to write x!! to assert the non-nullability inside the block.
Dart doesn't have non-nullable types (yet), so that distinction isn't important in Dart.
Just use if (x != null) { ... }.
If Dart gets non-nullable types, you can be assured that the null check in the condition will also promote x to non-nullable inside the block (if x is a local variable, is not mutated inside the block, other restrictions may apply).
(EDIT: Dart now has nullable types, and x != null promotes x to non-null.)
From your other comments, it sounds like you might be wanting the Kotlin behavior of x?.run { ... } instead, which binds this to x inside the lambda block. There is no corresponding feature in Dart. You cannot override this, it's always bound to the the object that the current method was called on, even inside nested closures which captures the value of this just as they capture other variables.
Using this extension:
extension Ext on Object? {
void ifNotNull(Function() action) {
if(this != null){
action();
}
}
}
You can achieve something similar:
object.ifNotNull(() => {
// safe code
});
I guess a closure does what you want
class Foo {
var x = 42;
void bar() {
() {
print(x);
doStuff();
doABitMoreStuff();
logStuff();
}();
}
}
Even though Dart doesn't have the let like behavior as of Kotlin but we can certainly emulate it with concise and readable code. Maybe something like this:
void main() {
String str = null;
str?.isEmpty ?? Function.apply(() {
print("Hey there you cheeky null valued variable");
}, []);
}
i implemented let function with extension function like this:
extension KotlinLet on Object?{
void let(Function callback ){
if (this != null) {
callback();
}
}
Object? also(){
if (this != null) {
return this;
}
}
}
You can simply use this package kotlin_flavor: https://pub.dev/packages/kotlin_flavor/install
There is no direct equivalent, because there is no need for it in Dart. Dart is a lot more like Java and you often end up with similar solutions.
There is almost no syntactic sugar in Dart. It's supposed to be easy to learn.
Also, Dart does not enforce strict null checks, all variables are nullable, and the language is single-threaded. That's why there is no need for let. Use if instead:
if(variable != null) {
doStuff();
doABitMoreStuff();
logStuff();
}
For given example:
class Base {
static abstract void foo();
}
class ChildA extends Base{
static void foo(){};
}
class ChildB extends Base{
static void foo(){};
}
I would like to find all subclasses of "Base" (to call foo on each).
I need to find this at build time (run time not required).
Only idea I have is to use reflections. But i don't know how to access class from ClassMirror?
This is what i have so far:
final mirror = currentMirrorSystem();
mirror.libraries.forEach((uri, libMirror) {
libMirror.classes.forEach((name, ClassMirror classMirror) {
try {
while ((classMirror = classMirror.superclass) != null) {
if (MirrorSystem.getName(classMirror.qualifiedName) == ".Base") {
//this is the classMirror of class i want
//but i have no idea how to access it
//or how to call foo() on it
print(classMirror);
print(classMirror.simpleName.toString());
}
}
} catch(e) {
print(e);
}
});
});
As mentioned I don't need this at run time so maybe a totally different approach would solve this problem. If not, question is: how do I call foo()?
thanks in advance.
Sorry guys, maybe SO related feature works better than search or maybe my research was not hard enough but anyhow I have found this:
Find all subclasses in dart
Answers there also suggested to use mirrors.
So to answer my own question a way to call static method foo is to use invoke method:
classMirror.invoke(#foo, []);
But this still is probably not an optimal solution, maybe there is a better way to do this at build time?
I thought I had this sorted, but I am still missing something.
Very simply, I have a Settings class that hold a DAO (sitting on a plist). I want to have a couple of enums for the settings for convenience and readability, such as GamePlayType and DifficultyLevel. Right now I am defining them in the Settings.h file above the #interface line as such:
typedef enum {
EASY,
NORMAL,
HARD
} DifficultyLevel;
and
typedef enum {
SET_NUMBER_OF_MOVES,
TO_COMPLETION
} GamePlayType;
If I access them from within the Settings class like:
- (int)gridSizeForLOD {
switch ([self difficultyLevel]) {
case EASY:
return GRID_SIZE_EASY;
case NORMAL:
return GRID_SIZE_NORMAL;
case HARD:
return GRID_SIZE_HARD;
default:
return GRID_SIZE_NORMAL;
}
}
everything is fine.
But, if I try to access them outside of the Settings class, let's say in my main view controller class, like this:
if (([settings gameType] == SET_NUMBER_OF_MOVES) && (numMoves == [settings numMovesForLOD])) {
[self showLoseScreen];
}
I get errors (like EXC_BAD_ACCESS) or the condition always fails. Am I doing something incorrectly?
Also, I should point out that I have this code for the call to gameType (which lives in the Settings class):
- (GamePlayType)gameType {
return [dao gameType];
}
and the DAO implements gameType like this:
- (int)gameType {
return (settingsContent != nil) ? [[settingsContent objectForKey:#"Game Type"] intValue] : 0;
}
I know I have the DAO returning an int instead of a GamePlayType, but A) the problem I am describing arose there when I tried to use the "proper" data type, and B) I did not think it would matter since the enum is just a bunch of named ints, right?
Any help, greatly appreciated. I really want to understand this thoroughly, and something is eluding me...
Cheers,
Chris
If you don't have it there already you'll need an import like below in your other class
#import "Settings.h"
I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface.
Here is how the class is going to be used:
ClassItem *pClassItem = myClass.Lookup(value);
if (pClassItem)
{ // item is found in class so modify and use it
pClassItem->SetAttribute(something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass).
To get round that the following could be considered:
bool found = myClass.Lookup(value);
if (found)
{ // item is found in class so modify and use it
myClass.ModifyAttribute(value, something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method:
bool found = myClass.LookupAndModify(value, something);
if (found)
{ // item is found in class
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well.
Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)?
Actually std::set<>::insert() does precisely this. If the value exists, it returns the iterator pointing to the existing item. Otherwise, the iterator where the insertion was made is returned.
It is likely that you are using a similar data structure for fast lookups anyway, so a clean public interface (calling site) will be:
myClass.SetAttribute(value, something)
which always does the right thing. MyClass handles the internal plumbing and clients don't worry about whether the value exists.
Two things.
The first solution is close.
Don't however, return ClassItem *. Return an "opaque object". An integer index or other hash code that's opaque (meaningless) to the client, but usable by the myClass instance.
Then lookup returns an index, which modify can subsequently use.
void *index = myClass.lookup( value );
if( index ) {
myClass.modify( index, value );
}
else {
myClass.add( value );
}
After writing the "primitive" Lookup, Modify and Add, then write your own composite operations built around these primitives.
Write a LookupAndModify, TryModify, AddIfNotExists and other methods built from your lower-level pieces.
This assumes that you're setting value to the same "something" in both the Modify and Add cases:
if (!myClass.AddIfNotExists(value, something)) {
// use myClass
}
Otherwise:
if (myClass.TryModify(value, something)) {
// use myClass
} else {
myClass.Add(value, otherSomething);
}