Global variable

Can we use same global variable name in mutiple screens ? For example...defined in screen1 and can access from scree2 or screen3 ?

No, you cannot refer a variable declared/defined in another screen. You can share it's value using calling screen with value and/or using tinyDB.

1 Like

Or you can choose not to use multiple screens but virtual screens.

The names do not need to be unique, but their values will be independent of one another.

Yes, as ABG said, you can re-use global variable NAMEs, in different screens, as the are protected/scoped by namespaces - Screen1, Screen2...

As previously mentioned, global variables are actually "screen global" and not "app global," so if you want to pass information between screens you need to store the contents of relevant globals in TinyDB or similar.

For anyone wondering why this is, it's a bit of a historic artifact. When App Inventor first came out it only supported building apps with a single screen. Thus, at the time global variables were truly global because the scope of screen was the global scope. When support for creating more than one screen was added this equivalence was lost.

A reason for this behavior is that the variables are actually defined as fields on the screen itself. Folks who know Java will recognize that there isn't really a way to define variables outside of a class translation unit, and so the "global" variables are connected to the screen class (internally App Inventor refers to this type as Form). When you open a new screen, it is a different class than the old screen so it doesn't share the same fields, thus you can create variable x on Screen1 and variable x on Screen2 and they do not interfere with one another.

1 Like