在DART中是否可以有配置文件?

7

I have this JavaScript class:

'use strict;'
/* global conf */

var properties = {
    'PROPERTIES': {
        'CHANNEL': 'sport',
        'VIEW_ELEMENTS': {
            'LOADER_CLASS': '.loader',
            'SPLASH_CLASS': '.splash'
        }
    }
};

在JavaScript中,我可以使用以下属性:properties.PROPERTIES.CHANNEL

请问如何在DART中实现类似的功能?有没有最佳实践可以参考?

2个回答

7

有不同的方法。

你可以创建一个地图。

my_config.dart

const Map properties = const {
  'CHANNEL': 'sport',
  'VIEW_ELEMENTS': const {
    'LOADER_CLASS': '.loader',
    'SPLASH_CLASS': '.splash'
  }
}

然后像这样使用它: main.dart
import 'my_config.dart';

main() {
  print(properties['VIEW_ELEMENTS']['SPLASH_CLASS']);
}

或者您可以使用类来获取正确的自动完成和类型检查

my_config.dart

const properties = const Properties('sport', const ViewElements('.loader', '.splash'));

class Properties {
  final String channel;
  final ViewElements viewElements;
  const Properties(this.channel, this.viewElements;
}

class ViewElements {
  final String loaderClass;
  final String splashClass;
  const ViewElements(this.loaderClass, this.splashClass);
}

main.dart

import 'my_config.dart';

main() {
  print(properties.viewElements.splashClass);
}

1
我也会选择第二个,但是来自JS的人通常更喜欢少一些类。对于浏览器应用程序中的其中一个解决方案,您需要将配置与应用程序一起编译。 - Günter Zöchbauer

2

针对上述使用类的答案,实现静态变量可能很方便,但缺点是仍然需要编译/重建。

class CONFIG {
  static final String BUILD = "Release";
  static final String DEPLOYMENT = "None";
}

这可以在导入后从另一个类中使用: ```python import 模块名称
模块名称.方法名() ``` 请注意保留HTML标签。
var xyz = CONFIG.BUILD;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接