10 C
London
Saturday, February 10, 2024

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


Flutter model: 3.13.9
isar model: ^3.1.0+1

After the creation of an entity within the utility every little thing it’s working nice and the gadgets are displayed till the appliance it’s faraway from processes (faraway from foreground). The issue that we encounter is that the entities usually are not displayed anymore after the appliance is faraway from foreground.
That is solely taking place on the bodily iPhone gadgets.
On the iPhone simulator and Android simulator or bodily gadgets every little thing works as anticipated.
Bellow it’s a code snippet containing all the important thing facets of the implementation.

import 'package deal:flutter/materials.dart';
import 'package deal:supplier/supplier.dart';
import 'package deal:isar/isar.dart';
import 'package deal:path_provider/path_provider.dart';
import 'package deal: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 Length(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 essential() 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) {
        strive {
          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 utility'),
        ),
        physique: Container(

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

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

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here