如何将现有的sqlite数据库添加到Flutter并作为卡片列表打印?

我一直在寻找解决问题的方法。许多人写了一些关于将现有SQLite数据库添加到Flutter的东西,但其中没有一个是确切的。

所以我的问题是如何在Flutter应用程序中添加现有的SQLite数据库(名为products.db)。我已经创建了产品的模型类,并在其中添加了带有products.db文件的资产文件夹,当然,我已经使用资产编辑了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'];

 }

}
iy5678 回答:如何将现有的sqlite数据库添加到Flutter并作为卡片列表打印?

@ Soner624,假定您遵循these的说明,并且您有一个product.db的实例,

  • 创建数据库函数来获取您的产品(我没有您的数据库信息,因此下面仅是一个示例,您可以了解一下。PRODUCTS_TABLE_NAME =您的表名,COLUMN_PRODUCT_ID =您的产品ID列名)
// 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;
}
  • 在应用程序中使用它(假设 assetDB 是您的products.db实例)以使用Card小部件显示产品列表,
  @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());
          }
        });
  }

希望这会有所帮助。祝你好运!

本文链接:https://www.f2er.com/3101603.html

大家都在问