Search code examples
flutterdartgetstorageflutter-getx

When and how should I use GetStorage.init(); with the get_storage package in flutter


I saw that most people use GetStorage.init(); in the first main() function of their projects like:

main() async {
  await GetStorage.init();
  runApp(App());
}

What if I call this function more often? When is the main function even called? When I started the App the first time? I want to understand when and how to call the GetStorage.init() function, and what the difference is when I only call it on a specific container like

GetStorage.init('MyStorage'); 

I couldn't print something after quitting the app to test the behavior.


Solution

  • Based on the documentation, you should really only use the GetStorage.init function once and in the first main function (recommended).

    The main function is the first function that is called whenever your app is opened by a user. You can use this function to retrieve local data, initializing firebase, and loads of other stuff.

    If you have more than one container then you should init all your containers. For example, you have two containers named "container1" and "container2". Then you should init them both like so

    GetStorage.init('container1');
    GetStorage.init('container2');
    

    based on my testing, if you retrieve a value from a non initialized container then it will always return null until the container have been initialized.

    IMPORTANT NOTE: You can init a container whenever you want, however initializing a container takes time and will not be instant (thus they are initialized at the start of the app and the await function that are used)