nisar
nisar

Reputation: 1065

How to create a dynamic variable in dart

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?

Upvotes: 5

Views: 11673

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658175

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.

Upvotes: 8

Related Questions