Detail explain “GetStorage” in Getx Flutter and some Advance concepts you have not used before
In Flutter, GetStorage
is a lightweight key-value storage system that allows you to persist data on the device. It is provided by the GetX
package, which is a popular state management and dependency injection library in Flutter.
GetStorage
is designed to be simple and easy to use. It uses a file-based storage system that allows you to store data as key-value pairs. You can use GetStorage
to store any type of data, including strings, integers, booleans, lists, and maps.
To use GetStorage
, you first need to add the get_storage
package to your pubspec.yaml
file:
dependencies:
get_storage: ^2.0.3
Then, you need to import the package and initialize the storage system in your main void main()
function:
import 'package:get_storage/get_storage.dart';
void main() async {
await GetStorage.init();
runApp(MyApp());
}
Once you have initialized GetStorage
, you can use it to store and retrieve data:
import 'package:get_storage/get_storage.dart';
void storeData() {
final box = GetStorage();
box.write('username', 'john.doe');
box.write('age', 30);
box.write('is_logged_in', true);
}
void retrieveData() {
final box = GetStorage();
final username = box.read('username');
final age = box.read('age');
final isLoggedIn = box.read('is_logged_in');
print('Username: $username');
print('Age: $age');
print('Is Logged In: $isLoggedIn');
}
In the example above, we use GetStorage
to store a username, age, and a boolean value indicating whether the user is logged in. We retrieve the data using the read
method, which returns the value of the specified key.
One of the benefits of using GetStorage
is that it is very fast and efficient. Since it uses a file-based storage system, it is able to read and write data quickly, even for large data sets.
Another benefit of using GetStorage
is that it is very lightweight and does not require any additional dependencies. This makes it a great choice for simple projects or for storing small amounts of data.
In conclusion, GetStorage
is a simple and efficient key-value storage system that can be used to persist data in Flutter applications. It is provided by the GetX
package and is easy to use for storing any type of data on the device.
How to store List and Map, Ojbects in Getstorage
To store a list or an object in GetStorage
, you can use the write()
method, just like you would to store any other value. However, there are a few considerations to keep in mind when working with lists and objects.
To store a list, you can simply pass the list as the value to be stored. For example
import 'package:get_storage/get_storage.dart';
void main() async {
await GetStorage.init();
final box = GetStorage();
final myList = ['apple', 'banana', 'orange'];
box.write('fruits', myList);
final storedList = box.read('fruits');
print('Stored list: $storedList');
}
To store a Map
in GetStorage
, you can use the write()
method with the key-value pairs of the Map
as the value to be stored. For example:
import 'package:get_storage/get_storage.dart';
void main() async {
await GetStorage.init();
final box = GetStorage();
final myMap = {'name': 'John', 'age': 30};
box.write('person', myMap);
final storedMap = box.read('person');
print('Stored map: $storedMap');
}
In this example, we create a list of fruits and store it in GetStorage
using the write()
method. We then retrieve the stored list using the read()
method and print it to the console.
To store an object, you need to serialize the object to a string before storing it. One way to do this is to use the dart:convert
library and the jsonEncode()
function to convert the object to a JSON string. For example:
import 'dart:convert';
import 'package:get_storage/get_storage.dart';
class Person {
String name;
int age;
Person(this.name, this.age);
Map<String, dynamic> toJson() => {'name': name, 'age': age};
factory Person.fromJson(Map<String, dynamic> json) =>
Person(json['name'], json['age']);
}
void main() async {
await GetStorage.init();
final box = GetStorage();
final person = Person('John', 30);
final jsonString = jsonEncode(person.toJson());
box.write('person', jsonString);
final storedString = box.read('person');
final storedPerson = Person.fromJson(jsonDecode(storedString));
print('Stored person: $storedPerson');
}
In this example, we define a Person
class with toJson()
and fromJson()
methods to serialize and deserialize the object. We create a Person
object and convert it to a JSON string using jsonEncode()
. We then store the JSON string in GetStorage
using the write()
method.
To retrieve the stored object, we read the JSON string using the read()
method, decode it using jsonDecode()
, and create a new Person
object from the decoded JSON using the fromJson()
factory method. We then print the stored Person
object
Advance Feature in GetStorage
Certainly, here’s an example of using the GetStorage
listenable()
method to observe changes to stored values:
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
void main() async {
await GetStorage.init();
final box = GetStorage();
// Register a listener to observe changes to a stored value
box.listen('username', () {
final updatedUsername = box.read('username');
print('Username changed to: $updatedUsername');
});
// Write a value to storage and observe changes
box.write('username', 'john.doe');
// Update the stored value and observe changes again
box.write('username', 'jane.doe');
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GetStorage Example',
home: Scaffold(
appBar: AppBar(
title: Text('GetStorage Example'),
),
body: Center(
child: Text('Check the console output'),
),
),
);
}
}
In the example above, we first initialize GetStorage
and create a box
object. We then use the listen()
method to register a listener for the username
key. Whenever the value of this key is updated, the listener function is called, and the updated value is printed to the console.
Next, we write a value to storage using the write()
method, which triggers the listener function and prints the value of john.doe
to the console. Finally, we update the value of username
to jane.doe
, which again triggers the listener function and prints the updated value to the console.
Note that in this example, we don’t use the listener function to update the user interface. Instead, we simply print the updated value to the console. However, in a real-world application, you could use the listener function to update the user interface in response to changes in stored data.
here’s an example of using the writeIf()
method in GetStorage
:
Sure, here’s an example of using the `writeIf()` method in `GetStorage`:
```
In the example above, we use the `writeIf()` method to write a value to storage only if the condition `age > 18` is met. If the condition is not met, the value is not written to storage. Similarly, we use the `writeIfNull()` method to write a value to storage only if the key `username` does not already exist.
After writing the values, we retrieve them using the `read()` method and print them to the console. In this case, the output shows that the value of `age` was written to storage because the condition was met, and the value of `username` was written to storage because the key did not already exist.
import 'package:get_storage/get_storage.dart’;
void main() async {
await GetStorage.init();
final box = GetStorage();
// Write a value only if a condition is met
int age = 30;
box.writeIf(’age’, age > 18, age);
// Write a value only if the key does not already exist
box.writeIfNull(’username’, 'john.doe’);
// Read the stored values
final storedAge = box.read(’age’);
final storedUsername = box.read(’username’);
print(’Stored age: $storedAge’); // Output: Stored age: 30
print(’Stored username: $storedUsername’); // Output: Stored username: john.doe
}
for more https://pub.dev/packages/get_storage