flutterdartflutter-hive

When I close my app, my database is resetting


I am using the hive database to store the money variable. I want to access this database from different pages, so I defined the box on the globals.dart page. I just want this box to be null when the application is first opened, but every time I open the application globals.box returns null and my money variable is resetting to 1000. How can I fix this?

This is my main file:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  globals.isLoggedIn = true;
  
  await Hive.initFlutter();
  await Hive.openBox<int>('stat');
  
  if (globals.box == null) {
    globals.box = Hive.box<int>('stat');
    globals.box.put('money', 1000);
  }
  runApp(MyApp());
}

This is my globals file

library my_prj.globals;
import 'package:hive/hive.dart';

bool isLoggedIn = false;
Box<int> box;

I am using this code to change the money variable:

import 'package:app1/globals.dart' as globals;    
globals.box.put('money', globals.box.get('money') + 100);

Solution

  • You can copy paste run two full code below
    Step 1: You can use globals.box = await Hive.openBox<int>('stat');
    Step 2: Check globals.box.get('money') == null, and set default value to 1000

    code snippet

      globals.box = await Hive.openBox<int>('stat');
    
      if (globals.box.get('money') == null) {
        print("box is null, set defaul value to 1000");
        globals.box.put('money', 1000);
      } else {
        print("box is not null, current value is ${globals.box.get('money')}");
      }
    

    output for first time open App

    I/flutter ( 8143): box is null, set defaul value to 1000
    

    click button and second time open App

    I/flutter ( 8217): box is not null, current value is 1100
    

    full code main.dart

    import 'package:flutter/material.dart';
    import 'package:hive/hive.dart';
    import 'package:hive_flutter/hive_flutter.dart';
    import 'globals.dart' as globals;
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      globals.isLoggedIn = true;
    
      await Hive.initFlutter();
      globals.box = await Hive.openBox<int>('stat');
    
      if (globals.box.get('money') == null) {
        print("box is null, set defaul value to 1000");
        globals.box.put('money', 1000);
      } else {
        print("box is not null, current value is ${globals.box.get('money')}");
      }
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  onPressed: () {
                    globals.box.put('money', globals.box.get('money') + 100);
                  },
                  child: Text("click"),
                ),
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    

    full code globals.dart

    library my_prj.globals;
    import 'package:hive/hive.dart';
    
    bool isLoggedIn = false;
    Box<int> box;