diff --git a/lib/database/pokedex_database.dart b/lib/database/pokedex_database.dart index 39d734c..fd5064f 100644 --- a/lib/database/pokedex_database.dart +++ b/lib/database/pokedex_database.dart @@ -43,6 +43,21 @@ class PokedexDatabase { onDatabaseUpdate.value++; } + // Méthode qui permet d'insérer plusieurs Pokémon d'un coup (plus performant) + static Future batchInsertPokemon(List pokemonList) async { + Database db = await getDatabase(); + Batch batch = db.batch(); + for (var pokemon in pokemonList) { + batch.insert( + 'pokemon', + pokemon.toJson(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + await batch.commit(noResult: true); + onDatabaseUpdate.value++; + } + // Méthode qui permet de récupérer la liste des pokémons dans la base de données static Future> getPokemonList() async { Database database = await getDatabase(); diff --git a/lib/pages/pokemon_list.dart b/lib/pages/pokemon_list.dart index 792ab34..adfe454 100644 --- a/lib/pages/pokemon_list.dart +++ b/lib/pages/pokemon_list.dart @@ -38,18 +38,16 @@ class _PokemonListPageState extends State { final count = await PokedexDatabase.getCaughtCount(); - // Check if database is empty for initial sync + // Check if database needs sync (less than 1025 pokemon) List localData = await PokedexDatabase.getPokemonList(); - if(localData.isEmpty) { + if (localData.length < 1025) { try { final List remoteData = await PokemonApi.getAllPokemon(); - // Insert all - for (var p in remoteData) { - await PokedexDatabase.insertPokemon(p); - } + // Insert all missing pokemon using batch for performance + await PokedexDatabase.batchInsertPokemon(remoteData); localData = await PokedexDatabase.getPokemonList(); } catch (e) { - debugPrint(e.toString()); + debugPrint('Sync Error: $e'); } }