Android原生项目我们可以用productFlavors设置不同环境下的不用域名、包名以及app名称等,但是flutter怎么做呢?
因为flutter和原生项目都需要根据变量进行不同的配置,所以必须找到一个原生和flutter都可以获取到的设置。
flutter支持在命令后面增加参数,如
flutter run --dart-define=key=value
同样也支持多个参数
flutter run --dart-define=key=value --dart-define=key2=value2
flutter代码获取参数
const envir = String.fromEnvironment(
'key',
defaultValue: 'prod'
);
if(envir == 'prod'){
...
}else{
...
}
然后我们就可以在代码里面根据获取到的值区分是测试环境还是线上环境
同样在Android gradle里面也可以获取到参数
不过flutter版本不同获取变量的方式也不同
1.17
//'dart-defines':key1=value1,key2=value2
def dartEnvironmentVariables = [
key: 'prod',
];
if (project.hasProperty('dart-defines')) {
dartEnvironmentVariables = dartEnvironmentVariables + project.property('dart-defines')
.split(',')
.collectEntries { entry ->
def pair = entry.split('=')
[(pair.first()): pair.last()]
}
}
1.20
//'dart-defines':key1%3Dvalue1,key2%3Dvalue2
def dartEnvironmentVariables = [
key: 'prod',
];
if (project.hasProperty('dart-defines')) {
dartEnvironmentVariables = dartEnvironmentVariables + project.property('dart-defines')
.split(',')
.collectEntries { entry ->
def pair = URLDecoder.decode(entry).split('=')
[(pair.first()): pair.last()]
}
}
2.2
//'dart-defines':a2V5MT12YWx1ZTE=,a2V5Mj12YWx1ZTI=
def dartEnvironmentVariables = [
key: 'prod',
];
if (project.hasProperty('dart-defines')) {
dartEnvironmentVariables = dartEnvironmentVariables + project.property('dart-defines')
.split(',')
.collectEntries { entry ->
def pair = new String(entry.decodeBase64(), 'UTF-8').split('=')
[(pair.first()): pair.last()]
}
}
根据获取到的参数自行改变包名或者app名称
if(dartEnvironmentVariables.key == "DEV"){
applicationIdValue = "com.app.dev"
appName = "appname测试"
}else{
applicationIdValue = "com.app"
appName = "appname"
}