In this blog we will learn about how to use Value Type and Reference Type in Flutter.
Introduction :
Value Type and reference types in Flutter is essential for mastering how data is managed in your Flutter applications.
We’ll explore how value types in Flutter work by holding separate copies of data, and how reference types in Flutter function by referring to the same data location in memory.
By the end of this blog, you will have a comprehensive grasp of understanding value and reference types in Flutter, and how to use these concepts to optimize your Flutter projects.
Value Type :
Value types as data types where each variable holds its own copy of the data.
- Examples of Value Types :
- int : Represents integer values.
- double : Represents floating-point numbers.
- bool : Represents boolean values (
true
orfalse
). - String : Although strings can seem complex, they behave as value types in Dart.
- Characteristics of value Types :
- Immutability : Value types are often immutable , meaning their state cannot be changed after they are created.
- Stack Allocation : Value types are usually stored in the stack , making them light weight and fast yo access .
- Independent Copies : Assigning one value type variable to another results in two independent copies. Changes to one will not affect the other.
- Example :
1 2 3 4 5 6 |
void main() { int a = 10; int b = a; // b is a copy of a b = 20; // changing b doesn't affect a print('a: $a, b: $b'); // Output: a: 10, b: 20 } |
Reference Type :
Reference type as type where variables hold a reference to the data rather than the data itself.
- Examples of Reference Types :
- List : A collection of elements, such as an array.
- Map : A collection of key-value pairs.
- Set : A collection of unique elements.
- Object : The base class of all Dart classes.
- Characteristics of Reference Types:
- Mutability : Reference types are typically mutable, meaning their contents can be changed after they are created .
- Heap Allocation : Reference types are stored in the heap , which allows for more complex data structures but can be slower to access than stack – allocated data.
- Shared Reference : Assigning one reference type variable to another results in both variables pointing to the same memory location. Changes to one affect the other.
- Example :
1 2 3 4 5 6 |
void main() { List<int> listA = [1, 2, 3]; List<int> listB = listA; // listB references the same list as listA listB[0] = 10; // modifying listB also affects listA print('listA: $listA, listB: $listB'); // Output: listA: [10, 2, 3], } |
Conclusion :
In summary, value types and reference types in Dart (and consequently in Flutter) have distinct behaviours that can significantly impact how your app functions.
Value types are simple, independent copies stored in the stack, while reference types are complex, shared references stored in the heap.
And thanks for reading this blog for related data click here .
You can read more interesting blogs by mobikul .