flutter
  1. flutter-database

Flutter Database

Flutter provides various options for integrating databases into mobile applications. This guide will cover the basics of using a database in a Flutter app.

Syntax

The syntax for using a database in Flutter depends on the database plugin you choose. Here's a general example using the popular sqflite plugin:

import 'package:sqflite/sqflite.dart';

// Open the database
final database = openDatabase(
  // Path to the database
  'my_database.db',
  // Database version
  version: 1,
  // onCreate callback
  onCreate: (Database db, int version) async {
    // Create tables and define schema
    await db.execute(
      'CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
    );
  },
);

// Insert data into the database
await database.insert(
  'users',
  {'name': 'John Doe', 'age': 25},
);

Example

Consider a simple Flutter app that uses an SQLite database to store user information.

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  final database = openDatabase(
    'my_database.db',
    version: 1,
    onCreate: (Database db, int version) async {
      await db.execute(
        'CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
      );
    },
  );

  Future<void> addUser() async {
    await database.insert(
      'users',
      {'name': 'John Doe', 'age': 25},
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Database Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: addUser,
          child: Text('Add User to Database'),
        ),
      ),
    );
  }
}

Output

The output will be a simple Flutter app with a button. When the button is pressed, it adds a user to the SQLite database.

Explanation

  • The sqflite plugin is used to interact with SQLite databases in Flutter.
  • The openDatabase function is used to open or create a database.
  • The insert method is used to insert data into the database.

Use

Use a database in a Flutter app when you need to persistently store and retrieve data. This is useful for applications that require user authentication, caching, or any form of data storage.

Important Points

  • Choose a database plugin based on your specific requirements (e.g., sqflite for local databases, firebase_database for Firebase).
  • Always handle database operations asynchronously to avoid blocking the UI.
  • Consider using state management solutions like Provider or Riverpod to manage database connections and state.

Summary

Integrating a database into your Flutter app allows you to store and retrieve data efficiently. Whether it's local storage or a cloud-based solution, Flutter provides a variety of plugins to suit different database needs. Understand the requirements of your app and choose the appropriate database solution for seamless data management.

Published on: