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<dynamic>'
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.
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,
}
CodePudding user response:
print(get());
will give you Instance of Future<dynamic>
since get()
returns a Future object.
SOLUTION:
You need to await the actual value in the Future object by writing await
before get()
in a Future method.
Like this:
print(await get());
In your question above, this cannot work as the build method cannot be async. You can put the print(await get())
in a separate method and have it in your initState
.
Like this:
@override
void initState() {
super.initState();
callGet();
}
Future<void> callGet() async {
print(await get());
}
CodePudding user response:
You are printing the await Storage.getValue(StorageKeys.authTokenKey);
value, and as it is a Future, you get this message.
You should try to call it on your initState and then get the Hive value. When the value returns you cant print it.
Eg:
@override
void initState() {
super.initState();
Storage.getValue(StorageKeys.authTokenKey).then((value) => print(value));
}