Flutter CRUD Operations SQLITE Tutorial | Devhubspot

Flutter Screen UI App Flutter app UI design sqlite local db crud

Hello Friends, in this article I will teach you how to create a crud application in Flutter, crud operations in Flutter, crud application in Flutter + SQLite, SQLite, crud, crud with sqlite and flutter, crud application using Flutter and SQLite, crud operations using flutter and sqlite, crud using flutter and sqlite, crud in a flutter, flutter crud app, flutter crud operations, flutter crud application.

Create a Flutter App

If everything is properly set up, then to create a project we can simply run the following command in our desired local directory:

flutter create sqlite-crud

After we've set up the project, we can navigate inside the project directory and execute the following command in the terminal to run the project in either an available emulator or an actual device:

flutter run

Plugins

The plugins needed for this project are:

  1. sqflite: for manage local db
  2. path_providerFlutter plugin for finding commonly used locations on the filesystem
  3. pathThe path package provides common operations for manipulating paths: joining, splitting, normalizing, etc.

You can import the packages to your Flutter project by adding them to your pubspec.yaml file:

  sqflite: ^2.3.0
  path: ^1.8.3
  path_provider: ^2.1.1

First, we need to make some simple configurations to the default boilerplate code in the main.dart file. We'll remove some default code and add the following code

import 'package:crudsqlite/screens/home.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'CRUD List Sqlite',
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
          useMaterial3: true,
        ),
        home: HomeScreen());
  }
}

Before Starting the code create a db folder and create db_connection.dart file inner db folder and add the following code : 

import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';

class DBConnection {
  Future<Database> setDatabase() async {
    var directory = await getApplicationDocumentsDirectory();
    var path = p.join(directory.path, "crud_user.db");
    var database =
        await openDatabase(path, version: 1, onCreate: createDatabase);
    return database;
  }

  Future<void> createDatabase(Database database, int version) async {
    String sql =
        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, contact TEXT, description TEXT)";
    await database.execute(sql);
  }
}

After creating a repository.dart file inner db folder and add the following code : 

import 'package:crudsqlite/db/db_connection.dart';
import 'package:sqflite/sqlite_api.dart';

class Repository {
  late DBConnection dbConnection;
  Repository() {
    dbConnection = DBConnection();
  }

  static Database? _database;

  Future<Database?> get database async {
    if (_database != null) {
      return _database;
    } else {
      _database = await dbConnection.setDatabase();
      return _database;
    }
  }

  //insert User
  insertData(table, data) async {
    var connection = await database;
    return await connection?.insert(table, data);
  }

  //Read All Records
  readData(table) async {
    var connection = await database;
    return await connection?.query(table);
  }

  //Read by id Records
  readDataById(table, itemId) async {
    var connection = await database;
    return await connection?.query(table, where: 'id=?', whereArgs: [itemId]);
  }

  //update user
  updateData(table, data) async {
    var connection = await database;
    return await connection
        ?.update(table, data, where: "id=?", whereArgs: [data['id']]);
  }

  //delete user
  deleteData(table, itemId) async {
    var connection = await database;
    return await connection?.rawDelete("delete from $table where id=$itemId");
  }
}

After creating a model folder and create users.dart file inner model folder and add the following code : 

class User {
  int? id;
  String? name;
  String? contact;
  String? description;

  userMap() {
    var mapping = Map<String, dynamic>();
    mapping['id'] = id ?? null;
    mapping['name'] = name!;
    mapping['contact'] = contact!;
    mapping['description'] = description!;
    return mapping;
  }
}

After creating a services folder and create user_service.dart file inner services folder and add the following code : 

import 'dart:async';

import 'package:crudsqlite/db/repository.dart';
import 'package:crudsqlite/model/user.dart';

class UserService {
  late Repository _repository;

  UserService() {
    _repository = Repository();
  }

  //save user
  saveUser(User user) async {
    return await _repository.insertData('users', user.userMap());
  }

  //Read All Users
  readAllUsers() async {
    return await _repository.readData('users');
  }

  //Read by id
  readUserById(id) async {
    return await _repository.readDataById('users', id);
  }

  //edit Users
  updateUser(User user) async {
    return await _repository.updateData('users', user.userMap());
  }

  //delete Users
  deleteUser(userId) async {
    return await _repository.deleteData('users', userId);
  }
}
After Create home.dart stateful widget  file in the screens folder like screens/home.dart, then inside of it with the following code:

import 'package:crudsqlite/model/user.dart';
import 'package:crudsqlite/screens/add_user.dart';
import 'package:crudsqlite/screens/edit_user.dart';
import 'package:crudsqlite/screens/view_user.dart';
import 'package:crudsqlite/services/user_service.dart';
import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late List<User> userList = <User>[];
  final userService = UserService();

  getAllUserDetails() async {
    var users = await userService.readAllUsers();
    userList = <User>[];
    if (users == null) {
      setState(() {
        userList = [];
      });
    } else {
      users.forEach((user) {
        setState(() {
          var userModel = User();
          userModel.id = user['id'];
          userModel.name = user['name'];
          userModel.contact = user['contact'];
          userModel.description = user['description'];
          userList.add(userModel);
        });
      });
    }
  }

  @override
  void initState() {
    getAllUserDetails();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: const Text(
          "CRUD List Sqlite",
          style: TextStyle(color: Colors.white),
        ),
      ),
      body: ListView.builder(
        itemCount: userList.length,
        itemBuilder: (context, index) {
          return Card(
            child: ListTile(
              onTap: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => ViewUser(
                              user: userList[index],
                            ))).then((data) => {getAllUserDetails()});
              },
              leading: const Icon(Icons.person),
              title: Text(userList[index].name ?? ""),
              subtitle: Text(userList[index].contact ?? ""),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  IconButton(
                      onPressed: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => EditUser(
                                      user: userList[index],
                                    ))).then((data) => {getAllUserDetails()});
                      },
                      icon: Icon(Icons.edit, color: Colors.blue)),
                  IconButton(
                      onPressed: () {
                        deleteFormDialog(context, userList[index].id);
                      },
                      icon: Icon(Icons.delete, color: Colors.red))
                ],
              ),
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
                  context, MaterialPageRoute(builder: (context) => AddUser()))
              .then((data) => {getAllUserDetails()});
          ;
        },
        backgroundColor: Colors.blue,
        child: Icon(
          Icons.add,
          color: Colors.white,
        ),
      ),
    );
  }

  deleteFormDialog(BuildContext context, userId) {
    return showDialog(
        context: context,
        builder: (param) {
          return AlertDialog(
            title: const Text("Are you sure to delete!",
                style: TextStyle(color: Colors.teal, fontSize: 20)),
            actions: [
              TextButton(
                style: TextButton.styleFrom(
                    primary: Colors.white,
                    backgroundColor: Colors.red,
                    textStyle: const TextStyle(fontSize: 15)),
                child: const Text("Delete"),
                onPressed: () async {
                  var result = await userService.deleteUser(userId);
                  if (result != null) {
                    Navigator.pop(context);
                    getAllUserDetails();
                  }
                },
              ),
              TextButton(
                style: TextButton.styleFrom(
                    primary: Colors.white,
                    backgroundColor: Colors.blue,
                    textStyle: const TextStyle(fontSize: 15)),
                child: const Text("Close"),
                onPressed: () {
                  Navigator.pop(context);
                },
              )
            ],
          );
        });
  }
}

After Create add_user.dart stateful widget  file in the screens folder like screens/add_user.dart, then inside of it with the following code:

import 'package:crudsqlite/model/user.dart';
import 'package:crudsqlite/services/user_service.dart';
import 'package:flutter/material.dart';

class AddUser extends StatefulWidget {
  const AddUser({super.key});

  @override
  State<AddUser> createState() => _AddUserState();
}

class _AddUserState extends State<AddUser> {
  var userNameController = TextEditingController();
  var userContactController = TextEditingController();
  var userDescriptionController = TextEditingController();
  bool validateName = false;
  bool validateContact = false;
  bool validateDescription = false;
  final userService = UserService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: Text("Add user"),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.all(16.0),
          child: Column(
            children: [
              TextField(
                controller: userNameController,
                decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    hintText: 'Enter name',
                    labelText: "Name",
                    errorText:
                        validateName ? 'Name value can\'t be empty' : null),
              ),
              const SizedBox(
                height: 20.0,
              ),
              TextField(
                controller: userContactController,
                decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    hintText: 'Enter contact',
                    labelText: "Contact",
                    errorText:
                        validateName ? 'Contact value can\'t be empty' : null),
              ),
              const SizedBox(
                height: 20.0,
              ),
              TextField(
                controller: userDescriptionController,
                decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    hintText: 'Enter description',
                    labelText: "Description",
                    errorText: validateName
                        ? 'Description value can\'t be empty'
                        : null),
              ),
              const SizedBox(
                height: 20.0,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(
                      style: TextButton.styleFrom(
                          primary: Colors.white,
                          backgroundColor: Colors.blue,
                          textStyle: const TextStyle(fontSize: 15)),
                      onPressed: () async {
                        setState(() {
                          userNameController.text.isEmpty
                              ? validateName = true
                              : false;

                          userContactController.text.isEmpty
                              ? validateContact = true
                              : false;

                          userDescriptionController.text.isEmpty
                              ? validateDescription = true
                              : false;
                        });

                        if (validateName == false &&
                            validateContact == false &&
                            validateDescription == false) {
                          print("calling");
                          var user = User();
                          user.name = userNameController.text;
                          user.contact = userContactController.text;
                          user.description = userDescriptionController.text;

                          var result = userService.saveUser(user);
                          print(result);
                          Navigator.pop(context, result);
                        }
                      },
                      child: const Text("Save Details")),
                  SizedBox(
                    width: 10.0,
                  ),
                  TextButton(
                    style: TextButton.styleFrom(
                        primary: Colors.white,
                        backgroundColor: Colors.red,
                        textStyle: const TextStyle(fontSize: 15)),
                    child: const Text("Clear Details"),
                    onPressed: () {
                      userNameController.text = "";
                      userContactController.text = "";
                      userDescriptionController.text = "";
                    },
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

After Create view_user.dart stateful widget  file in the screens folder like screens/view_user.dart, then inside of it with the following code:

import 'package:crudsqlite/model/user.dart';
import 'package:flutter/material.dart';

class ViewUser extends StatefulWidget {
  final User user;
  const ViewUser({super.key, required this.user});

  @override
  State<ViewUser> createState() => _ViewUserState();
}

class _ViewUserState extends State<ViewUser> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: Text("View user"),
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(
                  "Name",
                  style: TextStyle(
                      color: Colors.blue,
                      fontSize: 16,
                      fontWeight: FontWeight.w600),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 30),
                  child: Text(
                    widget.user.name ?? "",
                    style: TextStyle(fontSize: 16),
                  ),
                )
              ],
            ),
            SizedBox(
              height: 20,
            ),
            Row(
              children: [
                Text(
                  "Contact",
                  style: TextStyle(
                      color: Colors.blue,
                      fontSize: 16,
                      fontWeight: FontWeight.w600),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 30),
                  child: Text(
                    widget.user.contact ?? "",
                    style: TextStyle(fontSize: 16),
                  ),
                )
              ],
            ),
            SizedBox(
              height: 20,
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Description",
                  style: TextStyle(
                      color: Colors.blue,
                      fontSize: 16,
                      fontWeight: FontWeight.w600),
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  widget.user.description ?? "",
                  style: TextStyle(fontSize: 16),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

After Create edit_user.dart stateful widget  file in the screens folder like screens/edit_user.dart, then inside of it with the following code:

import 'package:crudsqlite/model/user.dart';
import 'package:crudsqlite/services/user_service.dart';
import 'package:flutter/material.dart';

class EditUser extends StatefulWidget {
  final User user;
  const EditUser({super.key, required this.user});

  @override
  State<EditUser> createState() => _EditUserState();
}

class _EditUserState extends State<EditUser> {
  var userNameController = TextEditingController();
  var userContactController = TextEditingController();
  var userDescriptionController = TextEditingController();
  bool validateName = false;
  bool validateContact = false;
  bool validateDescription = false;
  final userService = UserService();

  @override
  void initState() {
    setState(() {
      userNameController.text = widget.user.name ?? "";
      userContactController.text = widget.user.contact ?? "";
      userDescriptionController.text = widget.user.description ?? "";
    });

    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: Text("Edit user"),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.all(16.0),
          child: Column(
            children: [
              TextField(
                controller: userNameController,
                decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    hintText: 'Enter name',
                    labelText: "Name",
                    errorText:
                        validateName ? 'Name value can\'t be empty' : null),
              ),
              const SizedBox(
                height: 20.0,
              ),
              TextField(
                controller: userContactController,
                decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    hintText: 'Enter contact',
                    labelText: "Contact",
                    errorText:
                        validateName ? 'Contact value can\'t be empty' : null),
              ),
              const SizedBox(
                height: 20.0,
              ),
              TextField(
                controller: userDescriptionController,
                decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    hintText: 'Enter description',
                    labelText: "Description",
                    errorText: validateName
                        ? 'Description value can\'t be empty'
                        : null),
              ),
              const SizedBox(
                height: 20.0,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(
                      style: TextButton.styleFrom(
                          primary: Colors.white,
                          backgroundColor: Colors.blue,
                          textStyle: const TextStyle(fontSize: 15)),
                      onPressed: () async {
                        setState(() {
                          userNameController.text.isEmpty
                              ? validateName = true
                              : false;

                          userContactController.text.isEmpty
                              ? validateContact = true
                              : false;

                          userDescriptionController.text.isEmpty
                              ? validateDescription = true
                              : false;
                        });

                        if (validateName == false &&
                            validateContact == false &&
                            validateDescription == false) {
                          print("calling");
                          var user = User();
                          user.id = widget.user.id;
                          user.name = userNameController.text;
                          user.contact = userContactController.text;
                          user.description = userDescriptionController.text;

                          var result = userService.updateUser(user);
                          print(result);
                          Navigator.pop(context, result);
                        }
                      },
                      child: const Text("Update Details")),
                  SizedBox(
                    width: 10.0,
                  ),
                  TextButton(
                    style: TextButton.styleFrom(
                        primary: Colors.white,
                        backgroundColor: Colors.red,
                        textStyle: const TextStyle(fontSize: 15)),
                    child: const Text("Clear Details"),
                    onPressed: () {
                      userNameController.text = "";
                      userContactController.text = "";
                      userDescriptionController.text = "";
                    },
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
Output:


Flutter Screen UI App Flutter app UI design sqlite local db crud
Comments

AdBlock Detected!

Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.