Flutter - 将 SQL 数据发送到 ListView

Flutter - Sending SQL data to a ListView

使用 flutter 包 sqflite 我已经设法将数据从新闻源保存到数据库,例如 titledescription 等等。

请花点时间看看这个按照我的结构创建的 database file 应用程序。

这就是我创建数据库的方式,以及我将数据从在线资源保存到数据库的方式。

var title = articles[index].title;
var description = articles[index].description;
var url = articles[index].url;
var urlToImage = articles[index].urlToImage;
var publishedAt = articles[index].publishedAt;

var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'saved_articles.db');

Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  // When creating the db, create the table
  await db.execute(
        'CREATE TABLE Article (id INTEGER PRIMARY KEY, title TEXT, description TEXT, url TEXT, urltoimage TEXT, publishedat TEXT)');
});

print(database);

print(databasesPath);

// Insert some records in a transaction
await database.transaction((txn) async {
  int id1 = await txn.rawInsert(
    'INSERT INTO Article(title, description, url, urltoimage, publishedat) VALUES("$title", "$description", "$url", "$urlToImage", "$publishedAt")'
  );
  debugPrint('inserted1: $id1');

});

我正在寻找一种方法,可以将这些数据直接发送到有序 ListView。这是收藏夹页面的最终目标,可将文章保存到用户设备以供离线查看。

这就是我检索特定数据以转换为底部 title 列表的方式。

var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'saved_articles.db');

Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  // When creating the db, create the table
  await db.execute(
        'CREATE TABLE Article (id INTEGER PRIMARY KEY, title TEXT, description TEXT, url TEXT, urltoimage TEXT, publishedat TEXT)');
});

List<Map> title = await database.rawQuery('SELECT title FROM Article');
List<Map> description = await database.rawQuery('SELECT description FROM Article');
List<Map> url = await database.rawQuery('SELECT url FROM Article');

这就是我用来向列表发送特定查询的方法,但我不确定从这里开始可以创建一个可行的结构来将此数据发送到所需的 ListView

List<Map> title = await database.rawQuery('SELECT title FROM Article');

谢谢

我不完全确定我理解你的问题,所以如果我遗漏了什么,请跟进。

我正在寻找一种将此数据直接发送到有序 ListView 的方法。

由此,我理解了您的问题,因为您只是想知道下一步该怎么做?

如果是这样,我建议您看一下:https://pub.dartlang.org/packages/jaguar_serializer

那这就是我要做的

  1. 按照 jaguar 的自述文件创建一个 Article 模型,或者创建一个手动函数将地图转换为 Article 的实例。

    import 'package:jaguar_serializer/jaguar_serializer.dart'; part 'article.jser.dart'; class Article { string title; string description; string url; etc... } 等..

  2. 运行 命令行工具

  3. 创建查询以获取所有文章的列表,例如(在 sql 中排序更快)

    'SELECT title, description, url FROM Article ORDER BY title'

  4. 将其映射到文章列表(再次查看 jaguar 自述文件以创建 JsonRepo。

    List<Article> articles = jsonRepo.decodeList<Complete>(response.body);

  5. 然后你就可以把你的文章传给flutter中的ListView了

    ListView.builder( padding: EdgeInsets.all(8.0), itemExtent: 20.0, itemBuilder: (BuildContext context, int index) { return Text('entry ${articles[index].title}'); }, )