Junior — Middle
What are the main differences between local and global variables in programming?
sobes.tech AI
Answer from AI
Local variables are declared inside functions or blocks and are only accessible within that block. They are created when entering the function and destroyed when exiting it. Global variables are declared outside functions and are accessible throughout the file or even the entire application (depending on scope). In Flutter (Dart), global variables can be used to store state or settings, but their excessive use can lead to maintenance difficulties.
Example:
int globalCounter = 0; // global variable
void increment() {
int localCounter = 0; // local variable
localCounter++;
globalCounter++;
print('Local: $localCounter, Global: $globalCounter');
}
void main() {
increment(); // Local: 1, Global: 1
increment(); // Local: 1, Global: 2
}
Here, localCounter is recreated each time, while globalCounter retains its value between calls.