Home > Mobile >  Flutter Singleton Usage without late
Flutter Singleton Usage without late

Time:12-08

I have learned the how can I use singleton class. After that, I wanted to use for my baseUrl class.

class BaseUrls {
  BaseUrls._();
  static BaseUrls get instance => BaseUrls._();
  final String baseUrl="https://pub.dev/packages/";
  late final String bloc="${baseUrl}bloc";
}

when I wants to use any variable for instance bloc, I can use it like

BaseUrls.instance.bloc

but when I wants to use baseUrl inside of the bloc variable, I'm encountering the init error. I have solved that problem thanks to late usage. But in this time, there is a performance problem of late. when I use the late, it is harmful for ram usage.

So, my question is How can I use that usage without late? I mean, I wanna use the base url and bloc variable with together.

I'm open the new usage or best practices. Many thanks.

CodePudding user response:

To use bloc variable without using late, you can define the bloc variable as a function that returns a string, and inside the function, you can use the baseUrl variable:

    class BaseUrls {
    BaseUrls._();
    static BaseUrls get instance => BaseUrls._();
    final String baseUrl="https://pub.dev/packages/";
    String get bloc => "${baseUrl}bloc";
    }

Now, you can access the bloc variable like this: BaseUrls.instance.bloc. Because bloc is a function, it will be evaluated every time it is accessed, which means the value of baseUrl will always be up-to-date.

CodePudding user response:

finally,I have found 2 ways. First one is use static for baseUrl. Second way is use get function instead of bloc variable.

Summary:

//FIRST ONE
class BaseUrls {
  BaseUrls._();
  static BaseUrls get instance => BaseUrls._();
  final String baseUrl="https://pub.dev/packages/";
  final String get bloc="${baseUrl}bloc";
}

//SECOND WAY
    class BaseUrls {
        BaseUrls._();
        static BaseUrls get instance => BaseUrls._();
        static const String baseUrl="https://pub.dev/packages/";
        final String bloc="${baseUrl}bloc";
        }

so, which one if I use ,app will be more performance? Should I use getter function or only use static to baseUrl? Thanks....

  • Related