0

Although I am using get_storage, GetX's equivalent for SharedPreferences, my question would be the same regardless of the method used for retrieving settings. Everything works as expected, but I don't understand what's happening with the GetStorage() object:

When the app starts:

void main() async {
  await GetStorage.init();
  runApp(MyApp());

An instance of GetStorage() is created, before any widgets are built. To me this seems like the newly created object is unassigned to any variable. And yet commenting out this line of code results in preferences not being loaded properly.

MyApp is a StatelessWidget that initiates construction of HomeWidget():

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeWidget(),
      // etc.

So, next:

class HomeWidget extends StatelessWidget {
  final timeController = Get.put(Controller());

  @override
  Widget build(BuildContext context) {
    return Scaffold();
    // etc.

Thus, when HomeWidget is created, an instance of Controller class is created, right?:

class Controller extends GetxController {
  final storedSettings = GetStorage();
  // other variables are initiated

  Controller() {
    // code reading values from storedSettings and assigning them to fields

Here's where I feel confused. I am assuming another instance of GetStorage() is now created, and the storedSettings variable points to it. (Is that right?) I can read from storedSettings in the constructor, so I assume storedSettings points to an object that was created before the Controller() object's constructor was called. (Is that right?)

Why wouldn't one want to declare a storedSettings field, for object level scope, but actually create the GetStorage() object only once, in the Controller class's constructor? In other words

Controller() {
  storedSettings = GetStorage();
  // code reading values from storedSettings

with no GetStorage() in main() or anywhere else?

EDIT: I have seen the SO post "Dart assigning to variable right away or in constructor?" which addresses part of my confusion. But I still don't get why there's an object created in main() and then again in Controller().

Al C
  • 4,875
  • 6
  • 39
  • 65

0 Answers0