I am moving java script to dart, in java script I create dynamic variable like
window["text" + pageNumber] = 123;
alert(window["text" + pageNumber]);
How can I do it with dart?
In Dart Window (the type of window) is a class. You can't dynamically add properties to a Dart class.
window["text" + pageNumber] = 123; would work with a Map. Object representation in JS is quite similar to a map and therefore this works there.
If another class implements the [] operator you could call it on instances of that class as well but it would still not add properties. What it actually does just depends on the implementation of the [] operator.
There are probably different ways in Dart to achieve what you want, but you didn't add details about what actual problem you try to solve.
You can use normal global variables in Dart like explained in
Global Variables in Dart.
For your use case you can create a global Map variable this way
final Map<String,int> myGlobals = <String,int>{};
to create a map that stores integer values with string names.
Set values with myGlobals['someName'] = 123; and read them with print(myGlobals['someName']);.
If you need to set a global value that is also available for JS libraries you might use, you can use dart-js-interop
import 'dart:js';
import 'dart:html';
main() {
int pagenumber = 5;
context['Window']['text$pagenumber'] = 123;
window.alert('${context['Window']['text$pagenumber']}');
}
Try it on DartPad.
Hint:
"text" + pageNumber doesn't work when pageNumber is not a string.
In Dart you can't add string and numbers.
"text" + pageNumber.toString() would work but 'text$pagenumber' is a more darty way to do this. In string interpolation toString() is called automatically for you.
See also Dart js-interop not working if .dart file isn't included.
Related
I was wondering if it was possible to access the values of fields in an object with their names in a manner analogous to accessing values in a map with the key names. For example, something like this
void main() {
MyData d=MyData();
List<String> fieldNames=['a','b','c'];
for(var name in fieldNames){
print('This is the value of the $name field: ${d[name]}}');
}
}
class MyData{
String a='A';
String b='B';
String c='C';
}
Of course, this doesn't work because Dart doesn't quite know what to make of d[name] because d is an object. But if d was a map, it would work. Like this.
void main() {
Map d=myData;
List<String> fieldNames=['a','b','c'];
for(var name in fieldNames){
print('This is the value of the $name field: ${d[name]}}');
}
}
Map myData={
'a':'A',
'b':'B',
'c':'C',
};
So my question is this. If I have a class, is there any way to treat it like a Map in the situations where I might want to refer to several of the field values indirectly via their names like I tried to do above? Or is this sort of trick not possible in a compiled language like Dart?
The short answer is "no". The longer answer is "noooooooo". :)
But seriously, the namespace of your program code is very separate from the data values that are managed by your code. This isn't JavaScript, where we can freely flow from code to data to code again.
What way would you recommend of getting the definition of (global) variable var as it is in the source code snippet int var = MACRO(5) + 5; using Clang/Libclang if I have var's definition cursor?
One way would be to use the cursor's extents to extract the definition from the source code, but are there other ways, like reconstructing the definition using the AST?
I'm trying to 'port' some script to the Dart. To learn how everything work etc.
But there is a problem - in JavaScript we can set and get any variable in the object.
In Dart we have a Map class. And I have no idea how to use it (there is not so many help from Dart API Reference).
Currently I have:
Map settings;
//Then I get an dynamic result of a function that gives either null or object.
settings = result ?? {};
settings.someVar = 5;
And this code produces the following error:
"The setter 'someVar' is not defined for the class 'Map'."
Of course I can just 'invent' a new class Settings, but is there any other solutions?
With a Map, you get and put values with the [] and []= operators. So in this case you would use it like so;
settings['someVar'] = 5;
You can also use the addAll method;
settings.addAll({'someVar': 5, 'someOtherVar': 10});
Dart API References: operator [], operator []=, addAll
I wish to have the sub-classes of a super-class "registered" by an arbitrary name - whenever I declare a sub-class I wish to also have it entered into the super-class.sub Map.
Is there any way to accomplish this outside of main()?
// base class
class Mineral{
final String formula;
static Map<String,Mineral> sub = {}
Mineral( this.formula );
}
// sub class - declare and register
class Mica extends Mineral{
Mica( String formula ) : super( formula );
}
Mineral.sub['mica'] = Mica; // oops!
when I run this, I get
Error: line 10 pos 1: unexpected token 'Mineral' Mineral.sub['mica'] = Mica;
assuming that executable code is not allowed outside main().
cannot put within the super-class since other sub-classes may declared later, outside the library.
Dart has no way to run code as part of a library being loaded.
Executable code can only be put inside methods, or in field initializers, and static field initializers are lazy so they won't execute any code until you try to read them.
This is done to ensure quick startup - a Dart program doesn't have to execute any code before starting the main library's "main" method.
So, no, there is no way to initialize something that isn't constant before main is called.
Either
Mineral.sub['mica'] = new Mica();
or
static Map<String,Type> sub = {};
When you assign Mica you assign the Type Mica. new Mica() is an instance of Mica that is of the kind Mineral and can be assigned to the map you declared.
edit
Maybe you want to initialize the sub map:
static Map<String,Mineral> sub = {'mica': new Mica()};
hint: the semicolon is missing in this line in your question.
For Testing purposes I'm trying to design a way to verify that the results of statistical tests are identical across versions, platforms and such. There are a lot things that go on that include ints, nums, dates, Strings and more inside our collections of Objects.
In the end I want to 'know' that the whole set of instantiated objects sum to the same value (by just doing something like adding the checkSum of all internal properties).
I can write low level code for each internal value to return a checkSum but I was thinking that perhaps something like this already exists.
Thanks!
_swarmii
This sounds like you should be using the serialization library (install via Pub).
Here's a simple example to get you started:
import 'dart:io';
import 'package:serialization/serialization.dart';
class Address {
String street;
int number;
}
main() {
var address = new Address()
..number = 5
..street = 'Luumut';
var serialization = new Serialization()
..addRuleFor(address);
Map output = serialization.write(address, new SimpleJsonFormat());
print(output);
}
Then depending on what you want to do exactly, I'm sure you can fine tune the code for your purpose.