Flutter Database CRUD Operation

0

Flutter Database CRUD Operation :


In this article i have described how to create database using SQFlite database under SQLITE database package.




import 'package:flutter/material.dart';

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Book Database',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late Future<Database> database;
  List<Book> bookList = [];

  @override
  void initState() async{
    super.initState();
    // Initialize the database
    database = openDatabase (
      join(await getDatabasesPath(), 'book_database.db'),
      onCreate: (db, version) {
        return db.execute(
          'CREATE TABLE books(id INTEGER PRIMARY KEY, title TEXT, price INTEGER)',
        );
      },
      version: 1,
    );
    // Run database operations
    _runDatabaseOperations();
  }

  Future<void> insertBook(Book book) async {
    final db = await database;
    await db.insert(
      'books',
      book.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  Future<List<Book>> books() async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query('books');
    return List.generate(maps.length, (i) {
      return Book(
        id: maps[i]['id'] as int,
        title: maps[i]['title'] as String,
        price: maps[i]['price'] as int,
      );
    });
  }

  Future<void> updateBook(Book book) async {
    final db = await database;
    await db.update(
      'books',
      book.toMap(),
      where: 'id = ?',
      whereArgs: [book.id],
    );
  }

  Future<void> deleteBook(int id) async {
    final db = await database;
    await db.delete(
      'books',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  Future<void> _runDatabaseOperations() async {
    var b1 = Book(id: 1, title: 'Let Us C', price: 300);

    await insertBook(b1);
    setState(() async {
      bookList = await books();
    });

   /* await updateBook(b1);
    setState(() async{
      bookList = await books();
    });

    await deleteBook(b1.id);
    setState(() async {
      bookList = await books();
    });*/
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Book Database')),
      body: FutureBuilder<List<Book>>(
        future: books(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                final book = snapshot.data![index];
                return ListTile(
                  title: Text(book.title),
                  subtitle: Text('ID: ${book.id}, Price: ${book.price}'),
                );
              },
            );
          } else if (snapshot.hasError) {
            return const Center(child: Text('Error loading books'));
          }
          return const Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class Book {
  final int id;
  final String title;
  final int price;

  Book({required this.id, required this.title, required this.price});

  Map<String, dynamic> toMap() {
    return {'id': id, 'title': title, 'price': price};
  }

  @override
  String toString() {
    return 'Book{id: $id, title: $title, price: $price}';
  }
}

إرسال تعليق

0تعليقات

POST Answer of Questions and ASK to Doubt

إرسال تعليق (0)