top of page

Data Persistence in Flutter


Data Persistence in Flutter

In today's app development landscape, databases play a crucial role in managing and storing data. Flutter, a popular cross-platform framework, offers various options for integrating databases into your applications.


In this blog, we will explore the fundamental database concepts in Flutter and provide code examples to illustrate their implementation. So, let's dive in and learn how to effectively work with databases in Flutter!


Introduction to Databases


A database is a structured collection of data that allows efficient storage, retrieval, and manipulation of information. In the context of app development, databases are used to store and manage data persistently, enabling apps to function seamlessly even when offline or across different devices.


Local Data Persistence in Flutter


Local data persistence refers to the storage of data on the device itself. Flutter provides several libraries and techniques for local data persistence.


Some popular options include:


Shared Preferences


Shared Preferences is a simple key-value store that allows you to store primitive data types such as strings, integers, booleans, etc. It's suitable for storing small amounts of data that don't require complex querying.

import 'package:shared_preferences/shared_preferences.dart';

void saveData() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString('username', 'JohnDoe');
}

void loadData() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String username = prefs.getString('username');
  print('Username: $username');
}

Hive


Hive is a lightweight and fast NoSQL database for Flutter. It offers a simple key-value store as well as support for more complex data structures. Hive is known for its excellent performance and ease of use.

import 'package:hive/hive.dart';

void saveData() async {
  var box = await Hive.openBox('myBox');
  await box.put('username', 'JohnDoe');
}

void loadData() async {
  var box = await Hive.openBox('myBox');
  String username = box.get('username');
  print('Username: $username');
}

SQLite Database Integration


SQLite is a widely used relational database management system (RDBMS) that provides a self-contained, serverless, and zero-configuration SQL database engine. Flutter offers seamless integration with SQLite, enabling you to create and manage structured databases efficiently.


Setting up SQLite in Flutter


To use SQLite in Flutter, you need to include the sqflite package in your pubspec.yaml file and import the necessary dependencies.

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

Future<Database> initializeDatabase() async {
  String path = join(await getDatabasesPath(), 'my_database.db');
  return await openDatabase(
    path,
    version: 1,
    onCreate: (Database db, int version) async {
      // Create tables and define schemas
      await db.execute(
        'CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)',
      );
    },
  );
}

Performing CRUD Operations with SQLite


Once the database is initialized, you can perform various CRUD (Create, Read, Update, Delete) operations on it using SQL queries.

Future<void> insertUser(User user) async {
  final db = await database;
  await db.insert(
    'users',
    user.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

Future<List<User>> getUsers() async {
  final db = await database;
  final List<Map<String, dynamic>> maps = await db.query('users');
  return List.generate(maps.length, (i) {
    return User(
      id: maps[i]['id'],
      name: maps[i]['name'],
    );
  });
}

Working with Firebase Realtime Database


Firebase Realtime Database is a NoSQL cloud-hosted database that enables real-time data synchronization across devices. It offers seamless integration with Flutter, allowing you to store and sync structured data easily.


Setting up Firebase Realtime Database


To use Firebase Realtime Database in Flutter, you need to create a Firebase project, add the necessary dependencies in your pubspec.yaml file, and configure Firebase in your Flutter app.


Performing CRUD Operations with Firebase Realtime Database


Firebase Realtime Database uses a JSON-like structure to store and organize data. You can perform CRUD operations using the Firebase SDK.

import 'package:firebase_database/firebase_database.dart';

void insertUser(User user) {
  DatabaseReference usersRef =
      FirebaseDatabase.instance.reference().child('users');
  usersRef.push().set(user.toJson());
}

void getUsers() {
  DatabaseReference usersRef =
      FirebaseDatabase.instance.reference().child('users');
  usersRef.once().then((DataSnapshot snapshot) {
    Map<dynamic, dynamic> values = snapshot.value;
    values.forEach((key, values) {
      print('ID: $key');
      print('Name: ${values['name']}');
    });
  });
}

Implementing GraphQL with Hasura and Flutter


GraphQL is a query language for APIs that provides a flexible and efficient approach to data fetching. Hasura is an open-source engine that provides instant GraphQL APIs over databases. By combining Flutter, Hasura, and GraphQL, you can create powerful and responsive apps with real-time data capabilities.


Setting up Hasura and GraphQL in Flutter


To integrate Hasura and GraphQL into your Flutter app, you need to set up a Hasura server and define your database schema. Then, use the graphql package in Flutter to interact with the GraphQL API.


Performing GraphQL Operations with Hasura and Flutter


With GraphQL, you can define queries and mutations to fetch and modify data from the server.

import 'package:graphql_flutter/graphql_flutter.dart';

void getUsers() async {
  final String getUsersQuery = '''
    query {
      users {
        id
        name
      }
    }
  ''';

  final GraphQLClient client = GraphQLClient(
    cache: GraphQLCache(),
    link: HttpLink('https://your-hasura-endpoint.com/v1/graphql'),
  );

  final QueryResult result = await client.query(QueryOptions(
    document: gql(getUsersQuery),
  ));

  if (result.hasException) {
    print(result.exception.toString());
  } else {
    final List<dynamic> users = result.data['users'];
    for (var user in users) {
      print('ID: ${user['id']}');
      print('Name: ${user['name']}');
    }
  }
}

Conclusion


In this blog, we explored various database concepts in Flutter and learned how to implement them using different database technologies. We covered local data persistence, SQLite integration, Firebase Realtime Database, and GraphQL with Hasura.


With these skills, you can efficiently manage and store data in your Flutter applications. Experiment with these concepts and choose the most suitable database solution based on your app's requirements.


Happy coding!


Remember to import the necessary packages and dependencies to execute the code examples provided in this blog.

Comments


Blog for Mobile App Developers, Testers and App Owners

 

This blog is from Finotes Team. Finotes is a lightweight mobile APM and bug detection tool for iOS and Android apps.

In this blog we talk about iOS and Android app development technologies, languages and frameworks like Java, Kotlin, Swift, Objective-C, Dart and Flutter that are used to build mobile apps. Read articles from Finotes team about good programming and software engineering practices, testing and QA practices, performance issues and bugs, concepts and techniques. 

Monitor & Improve Performance of your Mobile App

 

Detect memory leaks, abnormal memory usages, crashes, API / Network call issues, frame rate issues, ANR, App Hangs, Exceptions and Errors, and much more.

Explore Finotes

bottom of page