Search code examples
flutterdartmapspreferencesshared

Flutter : best way to store maps locally?


what is the best way to store data locally. Assuming that I'm creating an app that stores transaction and I need to save id(because they may be many transactions with the same name), title, amount and time. Can I do it with shared preferences or is there another way to do it ? Thank you for answering.


Solution

  • Shared Preference let you read and write key-value pairs in a couple of lines easily. but shared preference is not a solution for you to keep complex data. you should keep those data in a Database.

    There are two major types of options you have:

    1. Relational — these are the databases in the traditional sense. They don’t just store data but also the relationships between the data. SQLite is an example of a relational database.

    SQflite is an implementation of SQLite for Flutter. It affords you complete control over your database, queries, and relationships.

    Pros

    Total control over the database. A very efficient SQLite database for your app (given that you have pre-existing SQLite knowledge).

    Cons

    Writing out all your queries by hand can take a lot of time.

    Returned data from the database isn’t strongly typed from the start.

    It is potentially difficult to handle migrations on the device (when the schema changes between version updates for instance).

    It has no support for the web.

    1. NoSQL — these databases store data as documents. A schema is not enforced as is the case with a relational database. They are lightning-quick and handle huge unstructured pieces of data very well. MongoDB is an example of a NoSQL database.

    Hive — offline NoSQL storage

    Hive is an extremely fast NoSQL storage option for Flutter developers. Its biggest selling point is that it is completely native to Dart.

    Hive lets you store data as a HiveObject, which allows for some relations between objects as well. It stores objects in a box, but you can generate TypeAdapters for them.

    Creating a box is fairly simple:

    var box = await Hive.openBox('testBox');
    

    Reading and writing is just as easy:

    import 'package:hive/hive.dart';
    void main() async {
     var box = await Hive.openBox('testBox');
     box.put('name', 'David');
     
     print('Name: ${box.get('name')}');
    }
    

    This benchmark if picked up from the hive package readme page:

    enter image description here