DEV Community

Hemunt Sharma
Hemunt Sharma

Posted on

3 1

How to Create table In SQLite Database in a flutter

SQLite is the Plugin that stores the data in the device in the form of Tables.

It helps to maintain the data in rows and columns in the Mobile local directory. we can run SQL queries to perform CRUD operations (Create, Read, Update, delete)

So to start Using the Sqlite in flutter add the plugin in the dependencies:

dependencies:
  flutter:
    sdk: flutter

#dependencie of SQLITE
  sqflite: ^2.2.0+3
  path_provider: ^2.0.11

Enter fullscreen mode Exit fullscreen mode

Then make a separate file for using all the database queries and creating a database.

Import the statements and create the database helper class:

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


class DatabaseHelper{

}

Enter fullscreen mode Exit fullscreen mode

In this class create the future method for creating a database and which will return the database when needed.

There is an openDatabase() function that comes in the SQLite package, which takes three parameters. first takes the path of the database where the database file will be stored and the second one takes the onCreate call back function which calls when the database is not there in the provided path and needs to be created. third is the version that takes the integer value.

Here is the function for that:

  final String _tableName = "users";

  Future<Database> getDataBase() async {
    return openDatabase(
      join(await getDatabasesPath(), "usersDatabase.db"),
      onCreate: (db, version) async {
        await db.execute(
          "CREATE TABLE $_tableName (id TEXT PRIMARY KEY, name TEXT, imageUrl TEXT)",
        );
      },
      version: 1,
    );
  }

Enter fullscreen mode Exit fullscreen mode

Also created one variable that stores the table name.

So here is how to create the Database function which creates the local database table.

See how to flutter SQLite CRUD operations are performed with Example Code.

Thank you for reading

Happy Fluttering

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay