Search code examples
flutterdartriverpoddioflutter-isar

Why is my app stopping while inserting 955 registers from API to ISARDB


I'm working on an app that needs to save a big certain amount of registers such as clients, orders, and others, not using an internet connection because it is targeted to not fluent internet place.

So I'm doing this on my app for instance

Future<List<Client>> getAllClientsBySeller(
      {int limit = 10, int offset = 0}) async {
    final isar = await db;
    final isarClients =
        isar.clients.where().offset(offset).limit(limit).findAll();
    try {
      final response =
          await dio.get('/clients/seller?limit=${1500}&offset=${0}');
      final List<Client> clients = [];
      for (final client in response.data ?? []) {
        clients.add(ClientMapper.jsonToEntity(client));
        if (await isarClients.then((value) => value.isEmpty)) {
          isar.writeTxnSync(() {
            isar.clients.putAllSync(clients);
          });
        } else {
          return isarClients;
        }

        isar.writeTxnSync(() {
          isar.clients.putAllSync(clients);
        });
      }
      return isar.clients.where().offset(offset).limit(limit).findAll();
    } catch (e) {
      throw CustomError('Error: ($e)');
    }
  }

and using Riverpod's provider to watch on my main loading screen

ref.watch(clientsProvider.notifier);

works well, but the deal is my screen freezes while fetching the API and inserting it IsarDb, like this

enter image description here

after a while, when it has done making the insert to the local database it defrosts and works normally.

Is something I'm doing wrong or perhaps my way isn't the right one?


Solution

  • Synchronous operations, denoted by the Sync() suffix, mean that the operation is performed in a blocking manner. That is, the program execution waits for the operation to complete before moving on to the next line of code.

    Try to remove "writeTxnSync" and "putAllSync" and use "await". for example:

    await isar.writeTxn(() 
       async { await isarCollection.putAll(clients); 
    });