Search code examples
flutterdartasynchronoussharedpreferences

Read data using from the device as soon as an app opens in flutter


I am saving the app's theme to the device using SharedPreferences, in this way:

void _serializeTheme() async {
    SharedPreferences _preferences = await SharedPreferences.getInstance();
    _preferences.setString("theme", "dark");
}

Upon opening the app I can use _preferences.getString("theme") to detect the theme, but as SharedPreferences.getInstance() is async, I need to wrap the home of my application in a FutureBuilder which waits for the theme to load before displaying the page and renders a container while waiting. My problem is that for the brief time that the app spends loading the theme the screen flashes with the color of the container which, as I have no idea of which theme the user has saved before loading it, has to be a fixed color which may be in discordance with the background color of the home page. To prevent this is there a way I can load the theme before displaying anything at all?

So, is there a way to run an asyncronous function before opening the application? Or if this isn't fiesable, is there a way to read data syncronously from the device so that I could read it inside initState() so that I can know the theme that the user saved before rendering anyting?


Solution

  • In your case, I would get await data in before runApp(), Example:

    main()async{
    // Here 
    SharedPreferences _preferences = await SharedPreferences.getInstance();
    
       runApp(YourApp());
        
    }
    

    or

    void main() {
      runZonedGuarded(() async {
    // Here 
    SharedPreferences _preferences = await SharedPreferences.getInstance();
    
       runApp(YourApp());
        
      }, (_, s) {});
    }