如何在Flutter上获得风味名称?

pxyaymoc  于 2023-01-09  发布在  Flutter
关注(0)|答案(5)|浏览(149)

有没有可能获得口味名称Flutter side?适用于Android和iOS

    • 生成分级**
flavorDimensions "app"

productFlavors {
    dev {
        dimension "app"
        versionCode 2
        versionName "1.0.0"
    }
    qa {
        dimension "app"
        applicationId "com.demo.qa"
        versionCode 3
        versionName "1.0.2"
    }
}
cwtwac6a

cwtwac6a1#

只要每种风味都有不同的packageName,您就可以这样做:

enum EnvironmentType { dev, qa }

class Environment {
  EnvironmentType current;

  Environment() {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      switch (packageInfo.packageName) {
        case "com.demo.qa":
          current = EnvironmentType.qa;
          break;
        default:
          current = EnvironmentType.dev;
      }
    });
  }
}
y1aodyip

y1aodyip2#

你可以用jonahwilliams的解决方案。
1.创建应用程序时设置键值对:

flutter build apk --flavor=paid --dart-define=app.flavor=paid

1.访问Dart中的值:

const String flavor = String.fromEnvironment('app.flavor');

void main() {
  print(flavor);
}

这将在运行时打印“paid”。
其优点是可以在尚不支持风格的平台上使用,并且变量为const,缺点是必须为构建设置键-值对。

yduiuuwa

yduiuuwa3#

没有一种简单的方法可以知道风味名称,但是我建议您使用一个环境变量,例如从flutter_dotenv加载。
文件.env

FLAVOR=dev

文件主.dart

void main() async {
  await DotEnv().load('.env');
  final flavor = DotEnv().env['FLAVOR'];

  String baseUrl;
  if (flavor == 'dev') {
    baseUrl = 'https://dev.domain.com';
  } else if (flavor == 'qa') {
    baseUrl = 'https://qa.domain.com';
  } else {
    throw UnimplementedError('Invalid FLAVOR detected');
  }
}

这将允许您(作为开发人员)轻松地更改应用的行为,并无缝地从不同的环境切换。

zaqlnxep

zaqlnxep4#

只需为此编写一个通道方法。

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
        channel.setMethodCallHandler { call, result ->
            when (call.method) {
                "getFlavor" -> {
                    result.success(BuildConfig.FLAVOR)
                }
            }
        }
    }

比在dart中:

final flavor = await platform.invokeMethod("getFlavor");
sr4lhrrt

sr4lhrrt5#

我还没有看到任何关于如何直接从运行时配置中获取当前风格的答案,经过大量的搜索,我找到了这种方法:对于Android是相当简单的,把这个代码在您的MainActivity.kt:

private val CHANNEL = "flavor_channel"

  override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
      call, result ->
            when (call.method) {
                "getFlavor" -> {
                    result.success(BuildConfig.FLAVOR)
                }
            }
    }
  }

对于iOS,请将其放入AppDelegate.swift:

let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let flavorChannel = FlutterMethodChannel(name: "flavor_channel",
                                          binaryMessenger: controller.binaryMessenger)
flavorChannel.setMethodCallHandler({
  (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
  // This method is invoked on the UI thread.
  guard call.method == "getFlavor" else {
    result(FlutterMethodNotImplemented)
    return
  }
  self.receiveCurrentFlavor(result: result)
})

然后在AppDelegate类的底部创建此方法:

private func receiveCurrentFlavor(result: FlutterResult) {
    var config: [String: Any]?
        
    if let infoPlistPath = Bundle.main.url(forResource: "Info", withExtension: "plist") {
        do {
            let infoPlistData = try Data(contentsOf: infoPlistPath)
            
            if let dict = try PropertyListSerialization.propertyList(from: infoPlistData, options: [], format: nil) as? [String: Any] {
                config = dict
            }
        } catch {
            print(error)
        }
    }

    result(config?["Flavor"])
  }

现在我们需要让Flavor在infoDictionary中可用。在Xcode中,打开Runner/Info.plist并添加一个Map到${PRODUCT_FLAVOR}的关键Flavor:

现在,在Targets/Runner/Build Settings/User-Defined下添加一个设置PRODUCT_FLAVOR。为每个配置添加风味名称:

然后在Dart中:

final flavor =  await const MethodChannel("flavor_channel").invokeMethod("getFlavor");

那你就完了!

相关问题