Prevent "flicker" of states when using shared_preferences

Viewed 32

I'm loading values with the package shared_preferences and wonder if I can prevent Flutter from using a Future and maybe set the state of the Switch controller before it renders?

Like in the HTML world I would set state in the DOMContentLoaded event callback before rendering of the webpage but in Flutter I don't know if that's possible or how I do it.

Future<void> storeValueBool(String name, bool value) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setBool(name, value);
}

class _StartPageState extends State<StartPage> {
bool? _rememberMe;

Future<void> getSharedPrefs() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  setState(() {
    _rememberMe = prefs.getBool("RememberMe");
  });
}

@override 
void initState() {
  super.initState();
  _rememberMe = false;
  getSharedPrefs();
}

}

And the Switch looks like this:

Switch(
   value: _rememberMe ?? false,
   onChanged: (value) => {
   setState(() {
    _rememberMe = value;
    storeValueBool("RememberMe", value);
  })},
  activeColor: customMaterialColor("48A69D")
)

First the Switch is Disabled and after the Future is done (I guess) the Switch is set to Enabled:

(You can also see the same behavior with the TextField and the stored value 123) enter image description here

1 Answers

If you want the value to load before showing the page you can use a FutureBuilder on top the entire page and wait for the future before showing any of the UI elements. That way it won't flicker any elements as the value update when loaded.

You can show a CircularProgressIndicator, a blank screen or whatever while it's loading.

Example:

FutureBuilder<bool>(
        future: getFuture(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Column(
              children: [
                Text('Header'),
                TextField(),
                Switch(value: snapshot.data ?? false, onChanged: changeValue),
              ],
            );
          } else {
            return CircularProgressIndicator();
          }
        },
      ),
Related