Convert variable reference name to its value in Dart - dart

I'm trying to access the variable reference by its name given in a String type.
class A {
B b = B();
}
class B {
String c = "apple";
}
void main() {
A a = A();
print(a.b.c); // prints apple
/// now if I get this ref as a string eg:
final ref = "a.b.c";
/// want to access the same variable with its reference
print(<ref>); <------
}
Need this to create a dynamic functionality.
Already tried with the creation of the toJson() method. but we have to access more nested classes and update all the classes with toJson method.
please help if there is any other solution.

Related

I use Dart with visual studio code The method is not defined How can I solve this problem

void main() {
List a = ["aa", "bbb", "ccccc"];
Iterable b = a.iterator;
while (b.moveNext()) {
/*The method 'moveNext' isn't defined for the type 'Iterable'.
Try correcting the name to the name of an existing method,
or defining a method named 'moveNext'.dartundefined_method
*/
print(b.current);
/* The getter 'current' isn't defined for the type 'Iterable<dynamic>'.
Try importing the library that defines 'current',
correcting the name to the name of an existing getter,
or defining a getter or field named 'current'.dartundefined_getter
*/
}
}
Multiple problems. E.g. a.iterator does not return a Iterable but instead Iterator. Also, you should not write List since that means List<dynamic> in Dart which means you are loosing type information.
The easiest way is to just use final or var and let Dart automatically use the most precise type (e.g. List<String>):
void main() {
final a = ["aa", "bbb", "ccccc"];
final b = a.iterator;
while (b.moveNext()) {
print(b.current);
}
}

Is it possible to force a Type to be used only in static fields?

I'm working on a library, and I have a implementation pattern users are required to follow:
class MyView extends LibView {
static Foo f = Foo();
#override
void render(){
use(f); // f should be static, otherwise things not work correctly
}
}
I would like to tell the compiler that, if someone ever does this, it's incorrect:
class MyView {
Foo f = Foo(); // Error: Foo can only be used in Static field.
...
}
Anyone know if this is possible? I find it really hard to find good docs on these sorta of language details when it comes to dart.
[EDIT] Since the "why" question always comes up, imagine something like:
class ViewState{
Map<int, Object> props = {};
}
ViewState _state = ViewState();
class View {
View(this.state);
ViewState state;
static int _key1 = getRandomInt();
void render(){
print(state(_key1))
}
}
// These should both print the same value off of state since the 'random' int is cached
View(_state);
View(_state);
If the key's were not static, everything would compile fine, but they would not print the same results.
What you properly need are a singleton which can be created in different ways in Dart. One way is to use a factory constructor like this:
class Foo {
static final Foo _instance = Foo._();
factory Foo() => _instance;
// Private constructor only used internally
Foo._();
}
void main() {
final a = Foo();
final b = Foo();
print(identical(a, b)); // true
}
By doing it like this, there will only be one instance of Foo which are then shared each time an instance are asked for. The instance are also first created the first time it is asked for since static variables in Dart are lazy and only initialized when needed.
I just want to do the functional equivalent of
int someUniqueKey = 0, or MyViewEnums.someUniqueKey but do it with a typed object rather than a int/enym, like: Object<Foo> someUniqueKey = Object<Foo>(). In order for this to work with Objects, it needs to be static. It's similar to how int someUniqueKey = random.nextInt(9999) would have to be static in order to be used as a key that all instances could share. That way keys are auto-managed and unique, and people don't need to assign int's, strings, or whatever. It also has the advantage of letting me use the type later for compile time checks.
bool prop = getPropFromRef(_prop1Ref); //Will throw error prop1Ref is not Ref<bool>
I think I've figured out something that does the trick using darts package-level methods.
class Ref<T> {}
// Re-use existing ref if it already exists
Ref<T> getRef<T>(Ref<T> o) => o ?? Ref<T>();
class RefView {}
// In some other package/file:
class MyView extends RefView {
static Ref<bool> prop1Ref = getRef(prop1Ref);
static Ref<int> prop2Ref = getRef(prop2Ref);
}
This will make sure that prop1 and prop2 have the same values across all instances of MyView and it will throw an error if these are not static (since you can not pass an instance field before Constructor)
This still has the downside of a potential hard to spot error:
class MyView extends RefView {
static Ref<bool> prop1 = getRef(prop1);
static Ref<bool> prop2 = getRef(prop1); // passing prop1 to prop2's getRef, and they have the same<T>, compiler will miss it
}
But I think it might be preferable than having this potential error:
class MyView extends RefView {
//Both of these will fail silently, keys will change for each instance of MyView
Ref<bool> prop1 = getRef(prop1);
Ref<bool> prop2 = getRef(prop2);
}

Initialize a final variable with "this" in Dart

I have a class like this:
class A extends B {
final Property<bool> property = Property<bool>(this);
}
class Property<T> {
Property(this.b);
final B b;
}
But I get an error on this saying:
Invalid reference to 'this' expression.
I believe I can't access this at that moment, probably because the object reference is not ready yet.
So I tried other forms of initializing that variable like:
class A extends B {
final Property<bool> property;
A() : property = Property<bool>(this);
}
But I get the same error.
The only thing that works is:
class A extends B {
Property<bool> property;
A() {
property = Property<bool>(this);
}
}
Which needs me to remove the final variable declaration, which is something I don't want to.
How can I initialize a final variable in Dart that needs a reference to the object itself?
You can't reference this in any initializers as this hasn't yet been initialized itself, so you won't be able to set Property<bool> property to be final.
If you're just trying to prevent modification of the value of property from outside the instance, you can use a private member and provide a getter to prevent modification. Given your example, that would look something like this:
class A extends B {
// Since there's no property setter, we've effectively disallowed
// outside modification of property.
Property<bool> get property => _property;
Property<bool> _property;
A() {
property = Property<bool>(this);
}
}

How can i use user define fucntion to set default value for domain class variable in grails

Here Cycle is a domain class
class Cycle {
int lenght = 42
String[] monitor = new String[length]
static mapping = {
monitor defaultValue:"defaultstrval(length)"
}
def defaultstrval(int length)
{
String[] defaultval =new String[length]
for(int i=0;i<length;i++)
{
defaultval[i]=","
}
return defaultval
}
}
Is Domain class only accept sql function.I really need help with good example.
Rather than using the mapping closure to call your function you can simply call the function from your variable assignment like so
String[] monitor = defaultstravel(length)

Get private variable by reflection in dart

I would like to get private variable in an object in dart.
This variable has no getter so I want to do this with reflection.
I try many way but nothing works to me.
For exemple, when I do this:
var reflection = reflect(this);
InstanceMirror field = reflection.getField(new Symbol(fieldName));
I get an error:
No getter for fieldName.
It's normal because the variable hasn't getter.
How can I get this variable ?
EDIT with a test code:
Here is my reflect test (test variable is a reflectClass(MyClass))
reflectClass(Injector).declarations.keys.forEach((e) => test.getField(e, test.type.owner))
I get this error:
Class '_LocalInstanceMirror' has no instance method 'getField' with
matching arguments.
If I do this:
reflectClass(Injector).declarations.keys.forEach((e) => test.getField(e))
I get:
Class 'DynamicInjector' has no instance getter
'_PRIMITIVE_TYPES#0x1b5a3f8d'.
Same thing with values of declarations.
The error message you got is actually correct. The class has a getter for this field.
Dart implicitly creates getters for all and setters for all non-final/non-const fields.
It seems access to private members isn't yet supported in Dart2JS.
see https://code.google.com/p/dart/issues/detail?id=13881
Here an example how to access private fields:
(example from https://code.google.com/p/dart/issues/detail?id=16773)
import 'dart:mirrors';
class ClassWithPrivateField {
String _privateField;
}
void main() {
ClassMirror classM = reflectClass(ClassWithPrivateField);
Symbol privateFieldSymbol;
Symbol constructorSymbol;
for (DeclarationMirror declaration in classM.declarations.values) {
if (declaration is VariableMirror) {
privateFieldSymbol = declaration.simpleName;
} else if (declaration is MethodMirror && declaration.isConstructor) {
constructorSymbol = declaration.constructorName;
}
}
// it is not necessary to create the instance using reflection to be able to
// access its members with reflection
InstanceMirror instance = classM.newInstance(constructorSymbol, []);
// var s = new Symbol('_privateField'); // doesn't work for private fields
// to create a symbol for a private field you need the library
// if the class is in the main library
// var s = MirrorSystem.getSymbol('_privateField', currentMirrorSystem().isolate.rootLibrary);
// or simpler
// var s = MirrorSystem.getSymbol('_privateField', instance.type.owner);
for (var i=0; i<1000; ++i) {
instance.setField(privateFieldSymbol, 'test');
print('Iteration ${instance.getField(privateFieldSymbol)}');
}
}
using dson or serializable you can do it in next way:
library example_lib;
import 'package:dson/dson.dart';
// this should be the name of your file
part 'example.g.dart';
#serializable
class Example extends _$ExampleSerializable {
var _privateVar;
}
main() {
var example = new Example();
example['_privateVar'] = 'some value';
print('example._privateVar: ${example._privateVar}');
print('example["_privateVar"]: ${example["_privateVar']}");
}

Resources