首页 > 解决方案 > 如何将现有的 sqlite 数据库添加到 Flutter 并打印为卡片列表?

问题描述

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

所以我的问题是如何products.db在我的 Flutter 应用程序中添加一个现有的 SQLite 数据库(名为 )。我已经创建了产品的模型类并添加了一个包含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'];

 }

}

标签: androiddatabasesqliteflutterdart

解决方案


@Soner624,假设您按照这些说明操作并且您有一个 products.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());
          }
        });
  }

希望这可以帮助。祝你好运!


推荐阅读