5

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?

nisar
  • 1,055
  • 2
  • 11
  • 26

1 Answers1

8

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

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.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • thanks..How can I use variable text5 for my further use,becoz I am going to generate a dynamic elements for that I need to create dynamic variables to use further to refer that elements? so that I have use context['Window']['text$pagenumber'] = some input values...It is really hard to use!!! – nisar Jan 14 '16 at 11:11
  • sample my link to create tables dynamically,I need to save every elements variable name to further needes https://dartpad.dartlang.org/4d84583325590c467b19 , in that link how can I create dynamic value for table_row_ele variable. – nisar Jan 14 '16 at 11:24
  • 2
    Using `window` for this is a gross misuse in Dart. This is exactly one of the hacks using Dart free you from. Just create a global `Map` variable and give it a name that reveals its purpose and store your values there. I updated my answer. I have no idea what you mean by `table_row_ele` variable. – Günter Zöchbauer Jan 14 '16 at 11:52
  • 2
    I am going to use map. – nisar Jan 18 '16 at 06:10