Simplify Data Storage in Flutter with CacheStorage

Introduction:

In Flutter app development, efficient data storage and retrieval are essential for creating seamless user experiences. One powerful tool for achieving this is the `CacheStorage` class. This class, accompanied by the `FlutterSecureStorage` package, simplifies the process of storing and retrieving various types of data in your Flutter application. In this blog post, we will explore the capabilities of the `CacheStorage` class and demonstrate how to use it to read a string value from the cache.


What is CacheStorage?

The `CacheStorage` class is a utility class that provides convenient methods to store and retrieve data using the `FlutterSecureStorage` package. It offers a straightforward interface for storing and retrieving different types of data, such as strings, booleans, integers, and doubles.

Storing Data

To store data using `CacheStorage`, you can use the provided methods for each data type. Here are the available methods:

  • `storeString`: Stores a string value with the specified key.
  • `storeBool`: Stores a boolean value with the specified key.
  • `storeInt`: Stores an integer value with the specified key.
  • `storeDouble`: Stores a double value with the specified key.

These methods utilize the `FlutterSecureStorage` package to securely write the data to the cache.

Retrieving Data

Retrieving data from the cache is just as easy as storing it. The `CacheStorage` class provides corresponding methods for each data type. Here are the available methods:

  • `readString`: Retrieves a string value associated with the specified key.
  • `readBool`: Retrieves a boolean value associated with the specified key.
  • `readInt`: Retrieves an integer value associated with the specified key.
  • `readDouble`: Retrieves a double value associated with the specified key.

These methods internally use the `FlutterSecureStorage` package to read the data from the cache. If the requested value is not found, a default value is returned to ensure graceful handling of missing data.

Reading a String Value from the Cache

Let's take a closer look at reading a string value from the cache using the `readString` method. Suppose we have stored a string value with the key "myKey" in the cache. To retrieve this value, we can use the following code:

String value = await CacheStorage.readString("myKey");

The `readString` method returns the stored string value associated with the specified key. If the value is not found, an empty string is returned as a fallback.

Common class for CacheStorage

class CacheStorage {
  static const FlutterSecureStorage cache = FlutterSecureStorage();

  static Future<void> storeString(String key, String value) async =>
      await cache.write(key: key, value: value);

  static Future<void> storeBool(String key, bool value) async =>
      await cache.write(key: key, value: value.toString());

  static Future<void> storeInt(String key, int value) async =>
      await cache.write(key: key, value: value.toString());

  static Future<void> storeDouble(String key, double value) async =>
      await cache.write(key: key, value: value.toString());

  static Future<String> readString(String key) async =>
      await cache.read(key: key) ?? "";

  static Future<bool> readBool(String key) async =>
      boolEncode(await cache.read(key: key) ?? " ");

  static Future<int> readInt(String key) async =>
      int.tryParse(await cache.read(key: key) ?? "0") ?? 0;

  static Future<double> readDouble(String key) async =>
      double.tryParse(await cache.read(key: key) ?? "0") ?? 0;
}

Sample flutter code

import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shared Preferences Example',
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _textEditingController = TextEditingController();
  String _storedValue = "";

  @override
  void initState() {
    super.initState();
    _loadStoredValue();
  }

  Future<void> _loadStoredValue() async {
    String value = await CacheStorage.readString("myKey");
    setState(() {
      _storedValue = value;
    });
  }

  Future<void> _storeValue() async {
    String value = _textEditingController.text;
    await CacheStorage.storeString("myKey", value);
    setState(() {
      _storedValue = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Shared Preferences Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Stored Value:',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 10),
            Text(
              _storedValue,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: TextField(
                controller: _textEditingController,
                decoration: InputDecoration(
                  labelText: 'Enter a value',
                ),
              ),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: _storeValue,
              child: Text('Store Value'),
            ),
          ],
        ),
      ),
    );
  }
}

Conclusion

Efficient data storage and retrieval are crucial for any Flutter application. The `CacheStorage` class simplifies the process by providing easy-to-use methods for storing and retrieving various data types. With the help of the `FlutterSecureStorage` package, the `CacheStorage` class ensures secure data storage while maintaining a user-friendly interface. In this blog post, we explored the functionalities of the `CacheStorage` class and learned how to read a string value from the cache using the `readString` method.

By leveraging the capabilities of `CacheStorage`, you can enhance your Flutter app's performance and provide a seamless user experience. Start using `CacheStorage` in your Flutter projects today and streamline your data storage needs.

Comments

Popular posts from this blog

Error Handling in Flutter - Gradle issue

Understanding API integration with Getx State management

How to Make a Dynamic and Trending ListView with Flutter Widgets?