Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to get value from shared preferences in a non-async method

Tags:

I am trying to get some values saved in the SharedPreferences from a getter method of a class. But SharedPreferences.getInstance() returns a Future. Is there a way to obtain the SharedPreferences object in a non-async getter methods, for example:

import 'package:shared_preferences/shared_preferences.dart';

class MyClass {
  get someValue {
    return _sharedPreferencesObject.getString("someKey");
  } 
}

Is there something in Dart that is similar to .Result property in C#, for example getSomethingAsync().Result (https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.result?view=netframework-4.7.2)?

like image 561
Dean Avatar asked Mar 28 '19 15:03

Dean


People also ask

Where are shared preferences stored flutter?

Flutter shared preferences is actually implemented as an in-memory cache. The first time that you call SharedPreferences. getInstance() all the current values are read from NSUserDefaults (on iOS) and SharedPreferences (on Android) and cached in memory.

How do you store Boolean value in SharedPreferences in flutter?

SharedPreferences prefs = await SharedPreferences. getInstance(); bool boolValue = prefs. getBool('option'); Important: You can only save int, String, double or bool variables using SharedPreferences.

What does shared preferences do in flutter?

shared_preferences is a Flutter plugin that allows you to save data in a key-value format so you can easily retrieve it later. Behind the scenes, it uses the aptly named SharedPreferences on Android and the similar UserDefaults on iOS.


1 Answers

You can use FutureBuilder()

SharedPreferences sharedPrefs;

@override
Widget build(BuildContext context) {
  return FutureBuilder(
    future: _getPrefs(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        return YourFinalWidget();
      }
      return CircularProgressIndicator(); // or some other widget
    },
  );
}

Future<void> _getPrefs() async{
  sharedPrefs = await SharedPreferences.getInstance();
}
like image 142
CopsOnRoad Avatar answered Sep 23 '22 05:09

CopsOnRoad