简体   繁体   中英

What is the best way to define singleton properties in Flutter/Dart?

I am using flutter_easyLoading package for loaders in my flutter project. It says in the documentation that it creates a singleton and I have to define its properties only once somewhere and it would be available throughout the app. What is the best practice to define these properties?

Right now I am initializing its variables in a splash screen file like this.

class _SplashScreenState extends State<SplashScreen> {
  @override
  void didChangeDependencies() async {
    super.didChangeDependencies();
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.dark;
 }

Should I do it this way or maybe define some util method for all these properties.

You can use a factory constructor implement singleton classes in dart.

This is a simple example adapted to this context

 class EasyLoadingSingleton { static final EasyLoadingSingleton _easyloading = EasyLoadingSingleton._internal(); factory EasyLoadingSingleton() { return _easyloading; } EasyLoadingSingleton._internal(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM