gpt4 book ai didi

flutter - 在小部件之间进行切换时,常量变量是否更具性能?如果是,那么如何在应用程序的入口点实现这一点?

转载 作者:行者123 更新时间:2023-12-03 03:11:23 25 4
gpt4 key购买 nike

我尝试对Web和android使用相同的代码。代码不同的地方,我根据全局变量在小部件之间切换。
在小部件之间切换时使用非常量/非最终变量时,性能会变差吗?我在想,因为变量不是最终变量或常量,并且可以随时更改,所以Flutter将无法优化代码。真的吗?如果效率低下,如何使我的代码效率高?
例如。
我有两个主要文件,并在每个文件中设置我的AppType枚举
[appType.dart]

AppType appType; //can't think of how to make this constant or final
[android_main.dart]
void main() {
appType = AppType.and;
[web_main.dart]
void main() {
appType = AppType.and;
在我的小部件中,我切换到需要特定于Web或android的小部件的位置
if(appType == AppType.web)
return MyWidgetWeb();
else
return MyWeigetAnd();

最佳答案

是的,常量是更有效的方法,主要是因为摇树。
假设您具有以下类型:

enum AppType {
mobile,
web,
}

class Mobile {}

class Web {}
然后,当您写:
const type = AppType.web;

void main() {
if (type == AppType.web) {
print(Web());
}
else if (type == AppType.mobile) {
print(Mobile());
}
}
然后,在编译代码时,编译器会知道始终会到达 if块,而永远不会到达 else if
因此:
  • 条件已删除。编译后,代码将为:
    const type = AppType.web;

    void main() {
    // no `if` performed
    print(Web());
    }
  • Mobile不会 bundle 在可执行文件中,因此您的应用程序更轻便。

  • 要充分利用此行为,可以使用Dart“定义”(使用 int/bool/String.fromEnvironment),它允许您根据某些外部构建参数定义行为不同的常量。
    这样的常量看起来像是:
    const isWeb = bool.fromEnvironment('isWeb', defaultValue: false);
    然后可以使用 flutter runflutter build命令上的参数进行控制:
    flutter build <whatever> --dart-define=isWeb=true

    关于flutter - 在小部件之间进行切换时,常量变量是否更具性能?如果是,那么如何在应用程序的入口点实现这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62757169/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com