Reputation: 11
I've searching very long for a solution to my problem. Many people have written something about adding an existing SQLite database to Flutter but not any of them has been exact.
So my question is how do I add an existing SQLite database (named products.db
) in my Flutter application. I've already created the model class of the products and added an assets folder with the products.db
file in it and of course I've edited the pubspec.yaml
with the assets.
Here is my products.dart
model class:
class Products {
int _pid;
int _cid;
int _tid;
String _model;
String _description;
String _pictureURI;
double _price;
// Construktor
Products(this._pid, this._cid, this._tid , this._model, this._description, this._pictureURI,
this._price);
// getters
int get id => _pid;
int get cid => _cid;
int get tid => _tid;
String get model => _model;
String get description => _description;
String get pictureURI => _pictureURI;
double get price => _price;
// setters dont needed
// Extract a Product Object from a Map Oject
Products.fromMapOject(Map <String,dynamic> map) {
this._pid = map['pid'];
this._cid = map ['cid'];
this._tid = map ['tid'];
this._model = map ['model'];
this._description = map ['description'];
this._pictureURI = map ['pictureURI'];
this._price = map ['price'];
}
}
Upvotes: 1
Views: 1568
Reputation: 3003
@Soner624, assuming you followed these instructions and you have an instance of your products.db,
// Get product based on id
Future<Products> getProduct(Database assetDB, int id) async {
final db = assetDB;
var res = await db.query(PRODUCTS_TABLE_NAME, where: COLUMN_PRODUCT_ID + " = ?", whereArgs: [id]);
Products product = res.isNotEmpty ? Products.fromMap(res.first) : null;
return product;
}
// Get all products
Future<List<Products>> getAllProducts(Database assetDB) async {
final db = assetDB;
var res = await db.query(PRODUCTS_TABLE_NAME);
List<Products> list =
res.isNotEmpty ? res.map((c) => Products.fromMap(c)).toList() : [];
return list;
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getAllProducts(assetDB),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: List.generate(snapshot.data.length, (itemIndex) {
Products product = snapshot.data[itemIndex];
return Card(
child: ListTile(
leading: SizedBox(height: 50.0, width: 50.0, child: NetworkImage(product._pictureURI)),
title: Text(product._model),
subtitle: Text(product._description + ', ' + product._price),
));
}),
);
} else {
return Center(child: CircularProgressIndicator());
}
});
}
Hope this helps. Good luck!
Upvotes: 1