ios – Flutter isar not persisting data on physical iPhone local storage after application it is removed from foreground


Flutter version: 3.13.9
isar version: ^3.1.0+1

After the creation of an entity in the application everything it is working fine and the items are displayed until the application it is removed from processes (removed from foreground). The problem that we encounter is that the entities are not displayed anymore after the application is removed from foreground.
This is only happening on the physical iPhone devices.
On the iPhone simulator and Android simulator or physical devices everything works as expected.
Bellow it is a code snippet containing all the key aspects of the implementation.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:my_app/models/local_db.dart';
import 'dart:convert';
import 'dart:async';

/// model from my_app/models/local_db.dart - start
part 'local_db.g.dart';

@collection
class LocalDb {
  Id id = Isar.autoIncrement;

  List<int>? db;
}

/// model from my_app/models/local_db.dart - end

class DataBase {
  List favoriteFolders;
  List archivedFolders;

  DataBase({
    required this.favoriteFolders,
    required this.archivedFolders,
  });
}

class GeneralAppState extends ChangeNotifier {
  DataBase dataBase = DataBase(
    favoriteFolders: [],
    archivedFolders: [],
  );

  Future<Isar> getIsar() async {
    if (Isar.instanceNames.isEmpty) {
      final dir = await getApplicationDocumentsDirectory();
      return await Isar.open(
        [LocalDbSchema],
        directory: dir.path,
      );
    }

    return Future.value(Isar.getInstance());
  }

  Future<void> createOrLoadDataBase() async {
    await Future.delayed(const Duration(seconds: 1));
    final Isar isar = await getIsar();

    final existingDb = await isar.localDbs.where().findFirst();

    if (existingDb != null) {
      // LOAD DATABASE
      decodeDb(existingDb.db!);
    } else {
      // CREATE DATABASE
      final newDataBase = LocalDb()..db = encodeDb(dataBase);
      await isar.writeTxn(() async {
        await isar.localDbs.put(newDataBase);
      });
    }
  }

  List<int> encodeDb(DataBase db) {
    return utf8.encode(jsonEncode({
      'favoriteFolders': db.favoriteFolders,
      'archivedFolders': db.archivedFolders,
    }));
  }

  void decodeDb(List<int> bytes) {
    final db = jsonDecode(utf8.decode(bytes));

    dataBase.favoriteFolders = db['favoriteFolders'];
    dataBase.archivedFolders = db['archivedFolders'];
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => GeneralAppState()),

        /// other providers
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final StreamController<bool> localStorageInitializationControoler = StreamController<bool>.broadcast();

  @override
  void initState() {
    localStorageInitializationControoler.stream.listen((event) async {
      if (event) {
        try {
          await context.read<GeneralAppState>().createOrLoadDataBase();
        } catch (e) {
          /// error handleling
        }
      }
    });

    openDb(true);

    super.initState();
  }

  void openDb(bool event) {
    localStorageInitializationControoler.add(event);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('My application'),
        ),
        body: Container(

            /// List favorite folders
            ),
      ),
    );
  }
}

Executing a CRUD using flutter isar on local storage needed for iOS and android applications. Everything works fine in iOS simulator and Android simulator/physical devices but when testing the application on physical iPhone device the created entities are not persisted to local storage because they disappear after the application is removed from foreground processes.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img