How to save to local storage using Flutter?

Cover Image for How to save to local storage using Flutter?
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Saving Data to Local Storage in Flutter: A Beginner's Guide πŸ˜ŽπŸ’ΎπŸ“±

So, you're building a Flutter app and you want to save data to the local storage? πŸ€” Don't worry, we got you covered! In this guide, we'll explore how to save data to local storage using Flutter, without the need for device-specific code or external dependencies. Let's dive right in! πŸ’ͺπŸš€

Understanding the Options

In Android, you have various options like SharedPreferences, SQLite databases, or writing files to the device. But what about Flutter? πŸ€·β€β™€οΈ

When it comes to Flutter, you can save data locally using the following approaches:

  1. Shared Preferences: This method is similar to Android's SharedPreferences and allows you to store key-value pairs persistently.

  2. Local Database (SQLite): Flutter provides a built-in package called sqflite that enables you to interact with a local SQLite database. This is useful for storing more complex data structures.

  3. File System: If you simply need to read and write files, Flutter also provides APIs to interact with the file system.

Saving to Local Storage Using Shared Preferences

Saving data to local storage using the shared preferences package is straightforward and doesn't require much code. Here's how you can do it:

  1. Add the shared_preferences package to your pubspec.yaml file:

dependencies:
  shared_preferences: ^2.0.13
  1. Import the package in your Dart file:

import 'package:shared_preferences/shared_preferences.dart';
  1. Saving data to shared preferences:

Future<void> saveDataToPrefs(String key, String value) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString(key, value);
  print('Data saved successfully!');
}
  1. Retrieving data from shared preferences:

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

Remember to replace String with the appropriate data type based on your requirements.

Saving to Local Database (SQLite)

If you're dealing with more complex data structures or want the querying capabilities of a database, you can use the sqflite package for interacting with a local SQLite database in Flutter.

  1. Add the sqflite package to your pubspec.yaml file:

dependencies:
  sqflite: ^2.0.0+4
  1. Import the package in your Dart file:

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
  1. Creating a table and saving data:

Future<void> saveDataToDb(String name) async {
  final database = openDatabase(
    join(await getDatabasesPath(), 'my_database.db'),
    onCreate: (db, version) {
      return db.execute(
        'CREATE TABLE my_table(id INTEGER PRIMARY KEY, name TEXT)',
      );
    },
    version: 1,
  );
  final db = await database;
  await db.transaction((txn) async {
    await txn.rawInsert(
      'INSERT INTO my_table(name) VALUES(?)',
      [name],
    );
    print('Data saved successfully!');
  });
}
  1. Retrieving data from the database:

Future<List<Map<String, dynamic>>> getDataFromDb() async {
  final database = openDatabase(
    join(await getDatabasesPath(), 'my_database.db'),
  );
  final db = await database;
  final List<Map<String, dynamic>> maps = await db.query('my_table');
  return maps;
}

Make sure to customize the table name and column names according to your needs.

Saving to File System

If all you need is basic file read and write operations, Flutter also supports file system interactions. Here's an example:

  1. Writing to a file:

Future<void> writeToFile(String text) async {
  final file = await File('path_to_file.txt').create();
  await file.writeAsString(text);
  print('Data written to file!');
}
  1. Reading from a file:

Future<String> readFromFile() async {
  final file = File('path_to_file.txt');
  
  if (await file.exists()) {
    final contents = await file.readAsString();
    return contents;
  } else {
    return 'File not found!';
  }
}

Remember to replace 'path_to_file.txt' with the actual file path or name.

Conclusion

Saving data to local storage in Flutter doesn't have to be complicated! Whether you prefer shared preferences, local databases, or simple file system interactions, Flutter offers numerous options to suit your needs. πŸ“¦

Now that you know these techniques, go ahead and build amazing Flutter apps with the ability to persist data across sessions!

Do you have any other questions or tricks for saving data locally in Flutter? Let us know in the comments below! πŸ˜ŠπŸ‘‡

Happy Fluttering! πŸš€πŸ”₯

Download the code example from GitHub


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

πŸ”₯ πŸ’» πŸ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! πŸš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings πŸ’₯βœ‚οΈ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide πŸš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? πŸ€” Well, my

Matheus Mello
Matheus Mello