Flutter SQLite Firebase Dr r yesi smail ER
Flutter – SQLite, Firebase Dr. Öğr. Üyesi İsmail İŞERİ Ondokuz Mayıs Üniversitesi Mühendislik Fakültesi Bilgisayar Mühendisliği Bölümü Ekim 2020 ismail. iseri@omu. edu. tr https: //www. linkedin. com/in/dr-ismail-iseri/ https: //personel. omu. edu. tr/tr/ismail. iseri
Flutter veri tabanı işlemleri için 2 farklı paket sunmaktadır. sqflite – SQLite veritabanına erişmek ve bunları işlemek için kullanılır, firebase_database - Google'ın bulutta barındırılan No. SQL veritabanına erişmek ve bunları işlemek için kullanılır. 2
SQLite • SQLite veritabanı, fiili ve standart SQL tabanlı gömülü veritabanı motorudur. • Küçük ve zaman içinde test edilmiş veritabanı motorudur. sqflite paketi, SQLite veritabanı ile verimli çalışmak için birçok işlevsellik sağlar. • SQLite veritabanı motorunu işlemek için standart yöntemler sağlar. • sqflite paketinin sağladığı temel işlevler aşağıdaki gibidir – • Bir veritabanı oluşturmak ve açmak (open. Database metot) • SQL metodu işleme (execute metot) • İleri sorgu metotları kullanma (query metot) 3
• Sqflite paketini kullanarak standart bir SQLite veritabanı motorundan ürün bilgilerini depolamak ve almak için bir ürün uygulaması oluşturalım ve SQLite veritabanı ve sqflite paketinin arkasındaki konsepti anlayalım. 4
Adımlar • Create a new Flutter application in Android studio, product_sqlite_app. • Replace the default startup code (main. dart) with our product_rest_app code. • Copy the assets folder from product_nav_app to product_rest_app and add assets inside the *pubspec. yaml` file. flutter: assets: - assets/appimages/floppy. png - assets/appimages/iphone. png - assets/appimages/laptop. png - assets/appimages/pendrive. png - assets/appimages/pixel. png - assets/appimages/tablet. png 5
pubspec. yaml dosyasında sqflite paketini aşağıda gösterildiği gibi yapılandırın dependencies: sqflite: any pubspec. yaml dosyasında path_provider paketini aşağıda gösterildiği gibi yapılandırın dependencies: path_provider: any Burada path_provider paketi, sistemin geçici klasör yolunu ve uygulamanın yolunu almak için kullanılır. Herhangi birinin yerine sqflite'ın en son sürüm numarasını kullanın. 6
Veritabanında, name, price, vb. gibi ürün özelliklerinin yanı sıra ek alan olarak birincil anahtar, id'ye ihtiyacımız var. Bu nedenle, Product sınıfına id özelliğini ekleyin. Ayrıca, ürün nesnesini Map nesnesine dönüştürmek için to. Map adlı yeni bir yöntem ekleyin. from. Map ve to. Map, Product nesnesini serileştirmek ve deserileştirmek (serleştirmeyi kaldırmak) için kullanılır ve veritabanı işleme yöntemlerinde kullanılır. 7
class Product { final int id; final String name; final String description; final int price; final String image; static final columns = ["id", "name", "description", "price", "image"]; Product(this. id, this. name, this. description, this. price, this. image); factory Product. from. Map(Map<String, dynamic> data) { return Product( data['id'], data['name'], data['description'], data['price'], data['image'], ); } Map<String, dynamic> to. Map() => { "id": id, "name": name, "description": description, "price": price, "image": image }; } 8
SQLite ilgili işlevselliği yazmak için lib klasöründe Database. dart adlı yeni bir dosya oluşturun. Database. dart'ta gerekli import ifadesini içe aktarın. import 'dart: async'; import 'dart: io'; import 'package: path/path. dart'; import 'package: path_provider/path_provider. dart'; import 'package: sqflite/sqflite. dart'; import 'Product. dart'; 9
Burada aşağıdaki noktalara dikkat edin async, asenkron yöntemler yazmak için kullanılır. io, dosyalara ve dizinlere erişmek için kullanılır. path, dosya yollarıyla ilgili dart çekirdek yardımcı program işlevine erişmek için kullanılır. path_provider, geçici ve uygulama yolunu almak için kullanılır. sqflite, SQLite veritabanını işlemek için kullanılır. 10
Yeni bir sınıf SQLite. Db. Provider oluşturun Aşağıda belirtildiği gibi tekil tabanlı, statik bir SQLite. Db. Provider nesnesi bildirin - class SQLite. Db. Provider { SQLite. Db. Provider. _(); static final SQLite. Db. Provider db = SQLite. Db. Provider. _(); static Database _database; } 11
SQLite. DBProvoider nesnesine ve yöntemine statik db değişkeni üzerinden erişilebilir. SQLite. DBProvoider. db. <emthod> 12
Future <Database> türündeki veritabanını (Future option) almak için bir yöntem oluşturun. Veritabanının oluşturulması sırasında ürün tablosu oluşturun ve ilk verileri yükleyin. 13
Future<Database> get database async { if (_database != null) return _database; _database = await init. DB(); return _database; } init. DB() async { Directory documents. Directory = await get. Application. Documents. Directory(); String path = join(documents. Directory. path, "Product. DB. db"); return await open. Database( path, version: 1, on. Open: (db) {}, on. Create: (Database db, int version) async { await db. execute( "CREATE TABLE Product (" "id INTEGER PRIMARY KEY, " "name TEXT, " "description TEXT, " "price INTEGER, " "image TEXT" ")" ); await db. execute( "INSERT INTO Product ('id', 'name', 'description', 'price', 'image') values (? , ? , ? )", [1, "i. Phone", "i. Phone is the stylist phone ever", 1000, "iphone. png"] ); await db. execute( "INSERT INTO Product ('id', 'name', 'description', 'price', 'image') values (? , ? , ? )", [2, "Pixel", "Pixel is the most feature phone ever", 800, "pixel. png"] ); await db. execute( "INSERT INTO Product ('id', 'name', 'description', 'price', 'image') values (? , ? , ? )", [3, "Laptop", "Laptop is most productive development tool", 2000, "laptop. png"] ); await db. execute( "INSERT INTO Product ('id', 'name', 'description', 'price', 'image') values (? , ? , ? )", [4, "Tablet", "Laptop is most productive development tool", 1500, "tablet. png"] ); await db. execute( "INSERT INTO Product ('id', 'name', 'description', 'price', 'image') values (? , ? , ? )", [5, "Pendrive", "Pendrive is useful storage medium", 100, "pendrive. png"] ); await db. execute( "INSERT INTO Product ('id', 'name', 'description', 'price', 'image') values (? , ? , ? )", [6, "Floppy Drive", "Floppy drive is useful rescue storage medium", 20, "floppy. png"] ); } 14
Burada aşağıdaki metotlar kullanıldı get. Application. Documents. Directory − Uygulamanın dizin yolunu döndürür join − Sisteme özel yol oluşturmak için kullanılır. Bunu veritabanı yolu oluşturmak için kullandık. open. Database − Bir SQLite veritabanını açmak için kullanılır on. Open − Bir veritabanını açarken kod yazmak için kullanılır on. Create − Bir veritabanı ilk kez oluşturulurken kod yazmak için kullanılır db. execute − SQL sorgularını yürütmek için kullanılır. Bir sorguyu kabul eder. Sorgu yer tutucusuna (? ) Sahipse, değerleri ikinci bağımsız değişkende liste olarak kabul eder. 15
Veritabanındaki tüm ürünleri getirmek için örnek bir yöntem - Future<List<Product>> get. All. Products() async { final db = await database; List<Map> results = await db. query("Product", columns: Product. columns, order. By: "id ASC"); } List<Product> products = new List(); results. for. Each((result) { Product product = Product. from. Map(result); products. add(product); }); return products; Tüm ürün bilgilerini almak için query yöntemi kullanıldı. sorgu, tüm sorguyu yazmadan tablo bilgilerini sorgulamak için kısayol sağlar. query yöntemi, sütun, order. By vb. girdilerimizi kullanarak uygun sorguyu kendisi üretecektir. Tablodaki tüm satırları tutan sonuç nesnesini döngüye alarak ürün ayrıntılarını almak için Product’ın from. Map yöntemi kullanıldı. 16
Veritabanındaki ID ‘ye göre ürün getirmek için örnek bir yöntem Future<Product> get. Product. By. Id(int id) async { final db = await database; var result = await db. query("Product", where: "id = ", where. Args: [id]); return result. is. Not. Empty ? Product. from. Map(result. first) : Null; } Burada where and where. Args filtre uygulamak için kullanıldı. 17
Ürünü veritabanından eklemek, güncellemek ve silmek için 3 yöntem oluşturalım ( ekleme, güncelleme ve silme. ) insert(Product product) async { final db = await database; var max. Id. Result = await db. raw. Query( "SELECT MAX(id)+1 as last_inserted_id FROM Product"); var id = max. Id. Result. first["last_inserted_id"]; var result = await db. raw. Insert( "INSERT Into Product (id, name, description, price, image)" " VALUES (? , ? , ? )", [id, product. name, product. description, product. price, product. image] ); return result; } update(Product product) async { final db = await database; var result = await db. update("Product", product. to. Map(), where: "id = ? ", where. Args: [product. id]); return result; } delete(int id) async { final db = await database; db. delete("Product", where: "id = ? ", where. Args: [id]); } 18
The final code of the Database. dart is as follows − 19
void main() { run. App(My. App(products: SQLite. Db. Provider. db. get. All. Products())); } 20
- Slides: 20