如何访问 hierarch dart 类属性?

问题描述 投票:0回答:1

如何在 Dart 中管理不同类别的图像路径,例如徽标和背景?我尝试像 Java 中那样使用嵌套类,但 Dart 不支持!处理此问题的最佳实践或替代方案是什么?


void main() {
  print(Images.background.lake); // it dosn't work!
}

class Images {
  class Portrait {
    final traditional = 'assets/images/portrait/traditional.png';
    final environmental = 'assets/images/portrait/environmental.png';
  }

  class Background {
    final nature = 'assets/images/background/nature.png';
    final lake = 'assets/images/background/lake.png';
  }
}


flutter dart class
1个回答
0
投票

先解决方案:

void main() {
  print(Images.background.lake); // This will work!
}

class Images {
  static final Portrait portrait = Portrait();
  static final Background background = Background();
}

class Portrait {
  final String traditional = 'assets/images/portrait/traditional.png';
  final String environmental = 'assets/images/portrait/environmental.png';
}

class Background {
  final String nature = 'assets/images/background/nature.png';
  final String lake = 'assets/images/background/lake.png';
}


解决方案2:

void main() {
  print(Images.Portrait.traditional); // Access using static references
}

class Images {
  static const Portrait Portrait = _Portrait();
  static const Background Background = _Background();
}

class _Portrait {
  static const String traditional = 'assets/images/portrait/traditional.png';
  static const String environmental = 'assets/images/portrait/environmental.png';
}

class _Background {
  static const String nature = 'assets/images/background/nature.png';
  static const String lake = 'assets/images/background/lake.png';
}


© www.soinside.com 2019 - 2024. All rights reserved.