首先,您需要从csv构建一个sqlite数据库。这可以通过以下方式完成:
- 创建必要的表(users.sql)
CREATE TABLE users( firstname TEXT NOT NULL, lastname TEXT NOT NULL, dob TEXT NOT NULL );
创建sqlite数据库
sqlite3 database.db < users.sql
插入CSV数据
sqlite3 database.db .mode csv .import data.csv users
- 将database.db放入您的资产中,并将其添加到pubspec.yaml中。
flutter: # ... assets: - assets/database.db
- 在您的应用中,您必须将资产文件复制到“文档”中。这有点复杂。
// Construct a file path to copy database to Directory documentsDirectory = await getApplicationdocumentsDirectory(); String path = join(documentsDirectory.path, "asset_database.db"); // only copy if the database doesn't exist if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound){ // Load database from asset and copy ByteData data = await rootBundle.load(join('assets', 'database.db')); List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); // Save copied asset to documents await new File(path).writeAsBytes(bytes); }
- 最后,您可以像这样访问数据库。
Directory appDocDir = await getApplicationdocumentsDirectory(); String databasePath = join(appDocDir.path, 'asset_database.db'); this.db = await openDatabase(databasePath); initialized = true;
- 查询示例(this._initialize()是步骤6)
Future<List<Page>> search(String word, int parentId) async { if (!initialized) await this._initialize(); String query = ''' SELECt * FROM users LIMIT 25'''; return await this.db.rawQuery(query); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)