Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display app theme immediately in Flutter app

Tags:

flutter

Given the asynchronous nature of the Flutter shared_prefs plugin, how could one make sure that when an app is launched the correct theme settings are immediately displayed? I.e. no flash of the default theme followed by applying the correct theme once the shared_prefs have finished loading.

like image 922
Frank Harper Avatar asked Jun 06 '17 00:06

Frank Harper


2 Answers

When your build method requires waiting for a Future, it's a good time to break out FutureBuilder.

void main() {
  runApp(new FutureBuilder(
    future: SharedPreferences.getInstance(),
    builder: (_, snapshot) {
      return snapshot.hasData ?
             new MyApp(preferences: snapshot.data) :
             new LoadingScreen(); 
    },
  ));
}

A few tips for building apps with this pattern:

  • SharedPreferences.getInstance() is pretty fast. You app may look better with an empty Container as a black loading screen instead of a flash of colorful content. However, if you're loading other stuff at the same time, showing your logo makes more sense.

  • If you need to await multiple futures, you can use Future.wait or nest multiple FutureBuilders together.

like image 179
Collin Jackson Avatar answered Sep 24 '22 03:09

Collin Jackson


One way would be to delay the display of your main app with a loading screen. A pattern I've seen is:

main() async {
  runApp(new LoadingScreen());
  runApp(new App(await asyncStuff()));
}

You can call runApp as often as you like: https://docs.flutter.io/flutter/widgets/runApp.html

like image 23
Eric Seidel Avatar answered Sep 22 '22 03:09

Eric Seidel