【问题标题】:Flutter create listview with local sqlite fileFlutter 使用本地 sqlite 文件创建列表视图
【发布时间】:2020-01-11 07:29:14
【问题描述】:

使用 sqflite 从本地 sql 文件 (chinook.db) 创建列表视图 初步解决的问题: I/flutter(5084):“未来”的实例 参考代码:https://github.com/tekartik/sqflite/blob/master/sqflite/doc/opening_asset_db.md 感谢@aakash 的帮助

main.dart
body: Container(
        child: FutureBuilder(
          future: getSQL("albums"),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            print(snapshot.data);
            if (snapshot.data == null) {
              return Container(child: Center(child: Text("Loading...")));
            } else {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(snapshot.data[index].title),
                  );
                },
              );
            }
          },
        ),
      ),

getSQL.dart 
Future getSQL(String tableName) async {
  var databasesPath = await getDatabasesPath();
  var path = join(databasesPath, "chinook.db");
// Check if the database exists
  var exists = await databaseExists(path);
  if (!exists) {
    // Should happen only the first time you launch your application
    print("Creating new copy from asset");
    // Make sure the parent directory exists
    try {
      await Directory(dirname(path)).create(recursive: true);
    } catch (_) {}
    // Copy from asset
    ByteData data = await rootBundle.load(join("assets", "chinook.db"));
    List<int> bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    // Write and flush the bytes written
    await File(path).writeAsBytes(bytes, flush: true);
  } else {
    print("Opening existing database");
  }
// open the database
  var db = await openDatabase(path, readOnly: true);

  List<Map> list = await db.rawQuery('SELECT * FROM $tableName');
  List theList = [];
  for (var n in list) {
    theList.add(MyCategoryFinal(n["Title"]));
  }
  return (theList);
}
class MyCategoryFinal {
  final String title;
  MyCategoryFinal(this.title);
}

【问题讨论】:

    标签: flutter sqflite


    【解决方案1】:

    我通过为 sqflite 表创建一个类来解决这个问题,在该地图列表上运行一个循环并将这些地图项转换为对象列表。

    示例代码;

    List<ItemBean> items = new List();
        list.forEach((result) {
          ItemBean story = ItemBean.fromJson(result);
          items.add(story);
        });
    

    要创建对象,您可以使用https://app.quicktype.io/。在这里你可以传递 json 来为它生成类。

    之后,您可以使用 FutureBuilder 像这样创建您的列表视图

           FutureBuilder(
              future: MyService.getAllItems(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(child: CircularProgressIndicator());
                }
    
                return ListView.builder(
                  controller: listScrollController,
                  itemCount: snapshot.data.length,
                  reverse: true,
                  itemBuilder: (context, index) {
                    return Text(snapshot.data[index].itemName);
                  },
                );
              },
            ),
    

    【讨论】:

    • 无法从原始代码中添加类中的项目,下面添加了 Future ....List list = await db.rawQuery('SELECT * FROM $tableName'); //打印(列表); List theList = []; for (var n in list) { MyCategory theList = MyCategory(n["CategoryName"], n["CategoryDe​​scription"]); theList.add(theList); } 返回(列表); } 类 MyCategory { 最终字符串类别名称;最终字符串类别描述; MyCategory(this.categoryName, this.categoryDe​​scription); } 我做错了吗?
    • 您拥有相同名称的列表和 MyCategory 对象。这就是为什么您在添加项目时遇到问题的原因。当您在 for 循环中创建 MyCategory theList 时,它会创建一个替换原始 theList 的本地对象。在 for 循环中给你的对象一个不同的名字,或者你可以简单地添加项目而不创建像这样的对象theList.add(MyCategory(n["CategoryName"], n["CategoryDescription"]));
    • 感谢@aakash,解决了这个问题。已编辑的原始帖子以供参考
    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2011-04-20
    • 2022-01-16
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多