简体   繁体   English

在 Flutter/Dart 中定义 singleton 属性的最佳方法是什么?

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

I am using flutter_easyLoading package for loaders in my flutter project.我在我的 flutter 项目中使用flutter_easyLoading package 作为装载机。 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.它在文档中说它创建了一个 singleton,我只需在某个地方定义它的属性一次,它就可以在整个应用程序中使用。 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.我应该这样做还是为所有这些属性定义一些 util 方法。

You can use a factory constructor implement singleton classes in dart.您可以使用工厂构造函数在 dart 中实现 singleton 类。

This is a simple example adapted to this context这是一个适应这种情况的简单示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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