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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With