使用sqflite从本地chinook.db创建Flutter ListView(已解决Future实例问题)
解决Flutter中
Instance of 'Future'打印问题的方案 问题解决记录
- 已成功解决初始问题:之前调试时控制台输出
I/flutter ( 5084): Instance of 'Future'的异常情况 - 解决思路参考了sqflite加载资产数据库的实现逻辑
- 特别感谢@aakash的帮助
实现代码
main.dart 核心代码片段
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"); // 检查数据库是否存在 var exists = await databaseExists(path); if (!exists) { // 仅在首次启动应用时触发 print("Creating new copy from asset"); // 确保父目录存在 try { await Directory(dirname(path)).create(recursive: true); } catch (_) {} // 从资源文件复制 ByteData data = await rootBundle.load(join("assets", "chinook.db")); List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); // 写入并刷新字节数据 await File(path).writeAsBytes(bytes, flush: true); } else { print("Opening existing 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); }
内容的提问来源于stack exchange,提问作者Scott Summers
相关产品推荐
相关产品推荐

