Global variables may seem to be wonderful Flutter program components, since they are declared once and can be accessed by every function in the program. However, these variables are more costly than you may imagine, mostly because:
- If you delete one global variable you have to search through the whole program and refactor every function that has access to the deleted global variable
- They are hard to test, since you have to reset them between test cases
- It is hard to track changes since every function can modify global variables
All of the above reasons clarify why global variables should never be used in Flutter. In this tutorial, we will learn the cons of global variables in detail and also learn how to manage states in a more effective way.
Table of Contents
- What are global variables in Flutter?
- The disadvantages of using global variables in Flutter
- How to manage states in a better way
What are global variables in Flutter?
Global variables are public variables that can be accessed by every method and object in a Flutter program.
Global variables are alternatives of local variables, which are created in a method and are accessed within that method.
The difference between local and global variables is that local variables cannot be accessed by other methods in the same program — therefore, local variables have a limited scope when compared with global variables.
The disadvantages of using global variables in Flutter
The use of global variables in Flutter has been questioned and criticized and is often considered bad practice. Here are the disadvantages that come with the use of global variables:
Complex code maintenance process
Changing or removing one global variable triggers a chain reaction of events, as widgets and methods that use the global variable will be affected.
In case you want to change a global variable, you have to analyze how each widget accessing the global variable will be affected and make specific and necessary changes.
If you delete one global variable, you have to search through the whole program and refactor every function that has access to the deleted global variable.
Global variables make unit testing painful
If you change one module that has global variables, then you will have to reset it for the next tests.
It is hard to understand legacy code that uses global variables and getting to understand how the program flow works is even harder. It is hard to effectively test code that you do not understand, and debugging is hard because you will not know who altered the global variables.
Global variables lead to spaghetti code
It is hard to track changes since every function in a program can modify a global variable. The situation of using global variables In Flutter escalates if you are building a large application. Global variables are a recipe for disaster even if you are building small Flutter applications.
Global variables oppose encapsulation
Global variables make it impossible to implement encapsulation, which is an OOP concept that wraps code into a single unit. Encapsulation makes it safe and easy to maintain code. If you want to use encapsulation effectively, you have to ban global variables.
It takes a lot of discipline to regulate global variables since they create spaghetti code. However, there are some developers who will use global variables because they are in a small team and in some cases adverse to change.
But, global variables will cause challenges when it’s time to maintain the code regardless of the application’s size. If it is necessary to use global variables at least make them immutable.
In the next segment, you will learn state management libraries and packages that present better ways of managing variable states in a better way without hurting maintenance procedures.
How to manage states in a better way
Flutter is a cross-platform and a dynamic framework that collects and processes data from users.
From the switches to the radio buttons, data states have to be managed effectively. However, global variables add complexity to the data flow of the application. Global variables make it easy for data to mutate, and this can cause chaos in handling data that has been collected from the user.
State management packages such as the provider
can be used to alleviate problems that come with global variables. Here is a list of state package managers and libraries you can use to manage states:
Provider state management package
The provider
state manager package is widely used to collect widget state data and update widgets when states change.
When using a provider, only the affected widget will be updated in case of a data mutation. The provider reduces complexity when compared to global variables that change everywhere. The provider gathers data from widgets and listens to data changes that occur around the widget.
This package separates the application state from the UI, and provider
promotes applications maintenance and testing.
Use the following code snippet to add and use the provider
package plugin:
dependencies: flutter: sdk: flutter provider: ^3.1.0
The provider
package also allows you to share widget states with multiple classes:
void main() { runApp( MultiProvider( providers: [ ChangeNotifierProvider(create: (context) => CartModel()), Provider(create: (context) => SomeOtherClass()), ], child: const MyApp(), ), ); }
GetX
GetX is a lightweight Flutter library that promotes scalability as it allows you to decouple the view, dependency injection, presentation layer, and dependency injection.
It provides the following features:
- State management
- Dependency injection
- Navigation
- Route management
If you are looking for a library that conserves resources and consumption is minimal, GetX is the best for you.
To start using GetX in your Flutter application start, add get
to your pubspec.yaml file:
dependencies: get:
Next, import get
files that will be needed when using GetX library functions and components:
import 'package:get/get.dart';
Riverpod
The Riverpod project is similar to the provider
package — the only difference is that it distributes data in a unidirectional manner.
This state manager makes sure that your code is testable and easy to read as it removes nesting for combining objects. The special feature is that it detects errors during compiling. This will save you time as you will fix errors before they add flaws to your application during runtime.
Redux
Redux is a library that helps you to effectively manage the data state of your widgets. Redux is an architecture that executes the distribution of state data across widgets in an unidirectional manner. The library is great as it eliminates state duplication and you can test if the state result is true.
The SetState
method
Previously, we only covered Flutter packages and libraries that manage states.
There is a method called setState
that can be called when your widget changes data values. It will cause the UI to change according to the new state. You can add the code that does something when a state changes. Here is a basic implementation of the setState
in Flutter:
class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { _counter++; setState(() {}); }
Conclusion
In this tutorial, we have learned what global variables are in detail and why we should never use them in Flutter. In addition, we have explored various state management libraries you can use to manage states more effectively.
The post Why you shouldn’t use global variables in Flutter appeared first on LogRocket Blog.
from LogRocket Blog https://ift.tt/yowVvZC
Gain $200 in a week
via Read more