我有两个文件名为
abc.dart
String one = "One";
String two = "Two";
和xyz.dart
String one = "1";
String two = "2";
在我的应用程序中,我有一个 bool
值,如果它是 true
我想使用 one
作为 “One”
如果 false
,one
应该是 "1"
。
也就是说,我需要在 true
上导入 abc.dart
,在 false
上导入 xyz.dart
。
最佳答案
根据这个issue , 在 Flutter 中似乎是不可能的。
这是因为 Flutter 应用程序是 AOT(提前)编译的,因此它需要在编译时加载所有源。
因此,您的选择不是依靠动态模块导入,而是:
- 使用编译时常量
// letter.dart
class Letters {
final String one;
final String two;
const Letter(this.one, this.two);
}
// abc.dart
const ABC = Letters('one', two');
// xyz.dart
const XYZ = Letters('1', 2');
// main
import './abc.dart'
import './xyz.dart'
onPressedHandler() {
print(boolValue? abc.one : xyz.one);
}
- 将文件指定为 Assets 并在运行时解析它们。 documentation about using assets
关于Flutter/Dart 在运行时导入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57571761/