LoginSignup
6
1

More than 1 year has passed since last update.

Flutterのユニットテスト。Sqfliteをローカルファイルで動かす

Posted at

sqlite大好き!どうも、赤ちゃんです。ばぶー。男の子です。

Flutterでsqliteを使ったアプリを作りたいのですが、わざわざユニットテストで毎回XCodeでビルドなんてしているとパソコンの寿命と◯玉がどんどん縮んでいきそうですので、出来ればテストはさっぱり終わらせたい。

Flutterでお馴染みであろうsqfliteがあるのですが、これはiOSやAndroidなどには対応しているものの、Webに非対応になっています。つまり、sqlfliteをちゃんと動かそうと思ったら、その度にXCodeでビルドして、その間にせんべえをバリバリ食べなければならない。XCode重すぎ湿りすぎ。

そこで色々探してみたら、良いものを見つけましたので、シェアさせていただきます。

sqflite_common_ffi

その名も、sqflite_common_ffiです。ネイティブコードを実装しているらしく、sqfliteがiOSなどのシミュレーターのみであるに対し、sqflite_common_ffiはパソコン(Web)も対応しています。

ただラップされていないので、条件に応じて書き換える必要があります。以下、条件分岐でsqfliteとsqflite_common_ffiを使い分けているコードです。このような感じにデータベースを初期化すれば、後はどちらも通常通りに使えます。パソコン(Web)で実行した場合、ローカルにファイルが保存されますので、チェックも簡単ぴーこです。なお、文法チェックのみしています。動作確認は勘弁してください。

test.dart
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

const String dbFile = "data.db";
const String subDir = "data";
late String dbPath;
const version = 1;
late Database db;

//on database created
FutureOr onCreate(db, value) async {
  //Write here on database created
  //...
  //...
}

//initialize database
void initDB() async {
  late String path;

  //pc or others
  if (Platform.isLinux || Platform.isMacOS || Platform.isWindows) {
    //pc

    path = join(Directory.current.path, subDir);
    Directory(path).create();
    sqfliteFfiInit();
    final options = OpenDatabaseOptions(
      version: version,
      onCreate: (db, version) => onCreate(db, version),
    );
    db = await databaseFactoryFfi.openDatabase(path, options: options);
  } else {
    //others

    Directory dir = await getApplicationDocumentsDirectory();
    path = dir.path;
    db = await openDatabase(
      path,
      version: version,
      onCreate: (db, version) => onCreate(db, version),
    );
  }
}

以上、sqflite_common_ffiの回し者がお送りしました。

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1