Using SQLite and Local Storage with Flutter


In the world of mobile app development, data storage is quite important. Flutter allows you to store data in your app using both SQLite and local storage mechanisms. In this article, we will provide information about using SQLite and Local Storage with Flutter and explain it with examples.

Developing Apps with SQLite

SQLite is a lightweight and portable database solution. Commonly used in mobile apps, SQLite can be easily integrated with Flutter. Below is an example showing how you can perform data insertion and listing operations using SQLite in your Flutter app.

Installing Required Packages

First, you need to add the sqflite package, which is required to use SQLite in your app, to your project. Add the following line to your pubspec.yaml file:


dependencies:
  sqflite: ^2.0.0+4

Adding Data with SQLite

Below is a simple function you can use to add data to the database:


Future<void> addItem(String item) async {
  final db = await database;
  await db.insert(
    'items',
    {'name': item},
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

Listing Data with SQLite

You can create a function like the one below to list the data stored in your database:


Future<List<Map<String, dynamic>>> getItems() async {
  final db = await database;
  return await db.query('items');
}

Using Local Storage

Local storage is another method for storing simple data in Flutter. It is especially ideal for small pieces of data. You can store data in your app using the shared_preferences package.

Installing Required Packages

First, add the necessary shared_preferences package to your pubspec.yaml file:


dependencies:
  shared_preferences: ^2.0.6

Saving Data with Local Storage

An example you can use to save data to local storage:


Future<void> saveData(String key, String value) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString(key, value);
}

Reading Data with Local Storage

You can use the following method to read the saved data:


Future<String?> getData(String key) async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString(key);
}

Conclusion

Using SQLite and Local Storage with Flutter provides great flexibility in data management for your app. SQLite is suitable for large and complex data, while local storage is ideal for simpler use cases. With the examples provided in this article, you can easily implement these methods in your own Flutter application.