Search code examples
jsonfluttercachingrequeststore

Best strategy for locally storing remote data in Flutter


I have a Flutter app that has to request a considerable volume of JSON data from the network. This data has to be converted into a Map.

The remote data changes like every week or so, so I am looking for a way to "cache" or permanently store it in order not to have to request it every time the user opens the app.

What would be the best way to achieve this?


Solution

  • You can use Hive lib to Save your data

    import 'dart:io';
    
    import 'package:hive/hive.dart';
    
    part 'main.g.dart';
    
    @HiveType(typeId: 1)
    class Person {
      Person({required this.name, required this.age, required this.friends});
    
      @HiveField(0)
      String name;
    
      @HiveField(1)
      int age;
    
      @HiveField(2)
      List<String> friends;
    
      @override
      String toString() {
        return '$name: $age';
      }
    }
    
    void main() async {
      var path = Directory.current.path;
      Hive
        ..init(path)
        ..registerAdapter(PersonAdapter());
    
      var box = await Hive.openBox('testBox');
    
      var person = Person(
        name: 'Dave',
        age: 22,
        friends: ['Linda', 'Marc', 'Anne'],
      );
    
      await box.put('dave', person);
    
      print(box.get('dave')); // Dave: 22
    }