我一直在寻找解决我的问题的方法。许多人写了一些关于将现有的SQLite数据库添加到Flutter的东西,但其中没有一个是确切的。
所以我的问题是如何在Flutter应用程序中添加现有的SQLite数据库(名为products.db
)。我已经创建了产品的模型类,并在其中添加了带有products.db
文件的 Assets 文件夹,当然,我已经使用 Assets 编辑了pubspec.yaml
。
这是我的products.dart
模型类:
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'];
}
}
最佳答案
@ Soner624,假设您已按照these的说明进行操作,并且拥有一个product.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());
}
});
}
希望这可以帮助。祝好运!
关于android - 如何将现有的sqlite数据库添加到Flutter并作为卡片列表打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58859562/