首页 > 解决方案 > Flutter如何确保在Android Studio中每当应用程序热重载时调用一个函数?

问题描述

我有一个 Flutter 应用程序,它依赖于根据其运行环境设置的正确服务器 URL。但是,在热重载期间似乎没有调用我的函数。

我的顶部有main.dart

String TARGET_URL; /// TODO: Replace once figure out how to set environment Variables based on type of device.

void setTargetURLForEnv() async {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  if (Platform.isIOS) {
    IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
    if (iosDeviceInfo.isPhysicalDevice) {
      TARGET_URL = 'http://aws-server-url.com';
    } else {
      TARGET_URL = 'http://localhost:6900';
    }
  }
}

void main() async {
  runApp(App());
  setTargetURLForEnv();
}

TARGET_URL即使在 iOS 模拟器上运行,热重载也会导致为空。如何强制调用此方法?

标签: flutterdevops

解决方案


在 runApp(App()) 上方尝试 setTargetURLForEnv()。我认为因为它在 App() 之外,所以热重新加载应用程序不会执行该功能。尝试热重启('R')而不是终端中的热重载。


推荐阅读