hive icon indicating copy to clipboard operation
hive copied to clipboard

Hive for flutter just returns the Instance instead of the actual value

Open FrazeColder opened this issue 3 years ago • 1 comments

I have decided to go with hive as my settings/preference storage. However, I am not able to implement my Storage class correctly because the getValue method always returns Instance of 'Future' instead of the actual value. Does anyone know how to fix that?

My Storage class just contains the getValue and setValue which always opens the hive box and then either should set or get the value. Also, I have created the enum StorageKeys in order to have a set of keys and make sure I get or set the value to the deticated key.

Code sample main.dart

void main() async {

  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();

  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    routes: {
      "/": (context) => const Home(),
    },
  ));
}

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  get() async {
    return await Storage.getValue(StorageKeys.authTokenKey);
  }

  void set() async {
    await Storage.setValue(StorageKeys.authTokenKey, 'TestValue');
  }

  @override
  Widget build(BuildContext context) {
    set();
    print(get());

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: ChevronNavigation(),
      body: Container(),
    );
  }
}

storage.dart

class Storage {
  static const preferencesBox = '_storageBox';

  static Future<void> setValue(StorageKeys key, dynamic value) async {
    final storage = await Hive.openBox<dynamic>(preferencesBox);
    storage.put(key.toString(), value);
  }

  static dynamic getValue(StorageKeys key) async {
    final storage = await Hive.openBox<dynamic>(preferencesBox);
    return await storage.get(key.toString(), defaultValue: null) as dynamic;
  }
}

enum StorageKeys {
  authTokenKey,
}

FrazeColder avatar Mar 04 '22 21:03 FrazeColder

Because you set key of type StorageKeys instance not the actual String.

Replace key with key.name

Abdurrahman98XX avatar Sep 21 '22 05:09 Abdurrahman98XX

@FrazeColder are you able to split your storage class in an independent package ?

AristideVB avatar Feb 12 '23 10:02 AristideVB