Flutter在assets里打開現(xiàn)有數(shù)據(jù)庫文件

打開asset數(shù)據(jù)庫

添加資產(chǎn)

  • 將assets添加到文件系統(tǒng)中項(xiàng)目的根目錄。通常,我會(huì)創(chuàng)建一個(gè)assets文件夾并將文件放入其中:
assets/examples.db

  • pubspec.yaml在波動(dòng)部分中指定assets
flutter:
  assets:
    - assets/example.db

將數(shù)據(jù)庫復(fù)制到你的文件系統(tǒng)

你是要從資產(chǎn)中獲取全新副本還是始終復(fù)制資產(chǎn),取決于你的使用情況,具體取決于你的使用情況

  • 你是否正在修改資產(chǎn)數(shù)據(jù)庫
  • 你是否總是想要資產(chǎn)的全新副本
  • 你想針對性能和尺寸進(jìn)行優(yōu)化嗎

性能優(yōu)化

為了獲得更好的性能,你應(yīng)該僅復(fù)制資產(chǎn)一次(第一次),然后始終嘗試打開副本

import 'package:path/path.dart';
import 'dart:typed_data';
import 'package:flutter/services.dart';

var databasesPath = await getDatabasesPath();
var path = join(databasesPath, "demo_asset_example.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", "example.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
db = await openDatabase(path, readOnly: true);

優(yōu)化尺寸

在iOS上更好的是,你可以編寫一個(gè)本機(jī)插件來獲取資產(chǎn)文件路徑,并以只讀模式直接打開它。Android沒有這種能力

始終從資產(chǎn)中獲取新副本

var databasesPath = await getDatabasesPath();
var path = join(databasesPath, "demo_always_copy_asset_example.db");

// delete existing if any
await deleteDatabase(path);

// 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", "example.db"));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await new File(path).writeAsBytes(bytes, flush: true);

// open the database
var db = await openDatabase(path, readOnly: true);

定制策略

你可能希望有一個(gè)版本控制策略(尚未成為該項(xiàng)目的一部分),僅在assets db在構(gòu)建系統(tǒng)中更改時(shí)才復(fù)制它,或者還可能允許用戶修改數(shù)據(jù)庫(在這種情況下,你必須先復(fù)制它)。

打開它!

// open the database
Database db = await openDatabase(path);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容