iOS Development

ios – Flutter isar not persisting knowledge on bodily iPhone native storage after software it’s faraway from foreground

Spread the love


Flutter model: 3.13.9
isar model: ^3.1.0+1

After the creation of an entity within the software every little thing it’s working advantageous and the gadgets are displayed till the applying it’s faraway from processes (faraway from foreground). The issue that we encounter is that the entities will not be displayed anymore after the applying is faraway from foreground.
That is solely occurring on the bodily iPhone units.
On the iPhone simulator and Android simulator or bodily units every little thing works as anticipated.
Bellow it’s a code snippet containing all the important thing features of the implementation.

import 'bundle:flutter/materials.dart';
import 'bundle:supplier/supplier.dart';
import 'bundle:isar/isar.dart';
import 'bundle:path_provider/path_provider.dart';
import 'bundle:my_app/fashions/local_db.dart';
import 'dart:convert';
import 'dart:async';

/// mannequin from my_app/fashions/local_db.dart - begin
half 'local_db.g.dart';

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

  Checklist<int>? db;
}

/// mannequin from my_app/fashions/local_db.dart - finish

class DataBase {
  Checklist favoriteFolders;
  Checklist 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) {
      last dir = await getApplicationDocumentsDirectory();
      return await Isar.open(
        [LocalDbSchema],
        listing: dir.path,
      );
    }

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

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

    last existingDb = await isar.localDbs.the place().findFirst();

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

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

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

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

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

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

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

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

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

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

  @override
  void initState() {
    localStorageInitializationControoler.stream.pay attention((occasion) async {
      if (occasion) {
        attempt {
          await context.learn<GeneralAppState>().createOrLoadDataBase();
        } catch (e) {
          /// error handleling
        }
      }
    });

    openDb(true);

    tremendous.initState();
  }

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

  @override
  Widget construct(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      house: Scaffold(
        appBar: AppBar(
          title: const Textual content('My software'),
        ),
        physique: Container(

            /// Checklist favourite folders
            ),
      ),
    );
  }
}

Executing a CRUD utilizing flutter isar on native storage wanted for iOS and android purposes. Every thing works advantageous in iOS simulator and Android simulator/bodily units however when testing the applying on bodily iPhone machine the created entities will not be persevered to native storage as a result of they disappear after the applying is faraway from foreground processes.

One thought on “ios – Flutter isar not persisting knowledge on bodily iPhone native storage after software it’s faraway from foreground

  1. I would claim that a true assistance is involved in producing excellent posts. It’s my first time visiting your website, and I’m amazed at how much research you did to produce such a fantastic article. Fantastic work!

Leave a Reply

Your email address will not be published. Required fields are marked *