Skip to content

Instantly share code, notes, and snippets.

@easylive1989
Created September 22, 2023 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save easylive1989/bfbdc3be0b5f4d552e8f674208942544 to your computer and use it in GitHub Desktop.
Save easylive1989/bfbdc3be0b5f4d552e8f674208942544 to your computer and use it in GitHub Desktop.
2023鐵人賽_D8_5
import 'package:drift/drift.dart';
part 'my_database.g.dart';
class Products extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get type => text()();
}
@DriftDatabase(tables: [Products])
class MyDatabase extends _$MyDatabase {
MyDatabase(QueryExecutor e) : super(e);
@override
int get schemaVersion => 1;
Future<int> createProduct(String type) {
return into(products).insert(ProductsCompanion.insert(type: type));
}
Future<List<Product>> getAll() async {
return await select(products).get();
}
}
import 'my_database.dart';
class MyFavorites {
final MyDatabase database;
MyFavorites(this.database);
Future<void> add(Product product) async {
await database.createProduct(product.type);
}
Future<List<Product>> getAll() async {
return await database.getAll();
}
}
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'my_database.dart';
import 'my_favorites.dart';
main() {
test("add favorite", () async {
MyDatabase database = MyDatabase(NativeDatabase.memory());
var myFavorites = MyFavorites(database);
await myFavorites.add(const Product(id: 1, type: "book"));
expect(await myFavorites.getAll(), [const Product(id: 1, type: "book")]);
await database.close();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment