假设你的项目同时引用了some_package和other_package两个包,而这两个包又同时引用了
collection这个包,若这两个包引用了不同的
collection版本就会造成冲突。
some_package的依赖
dependencies:
collection: '1.8.1'
other_package的依赖
dependencies:
collection: '1.9.0'
其实最好的解决方法是让包的开发者配置包依赖的时候指定一个范围,而不是直接写死某个版本,至于如何配置包的版本范围,可以参考Flutter 指定依赖的package包版本及版本区间
例如还有第三个包third_package也引用了collection包,他们对collection的版本约束如下所示
>=1.7.0 // some_package的版本约束
^1.4.0 // other_package的版本约束
<1.9.0 // third_package的版本约束
假设collection目前已发布的版本如下,那么根据三个包对collection包的约束规则可以确定符合的版本区间为1.7.0>=version<1.9.0,那么如下版本中符合条件的版本为1.8.2
1.7.0
1.7.1
1.8.0
1.8.1
1.8.2
1.9.0
一般规范一点的包都会指定依赖包的约束范围,但是如果依赖是写死的且确实造成了冲突,那么还可以通过强制覆盖的方法,在我们的项目中指定一个版本
例如上面的例子中some_package中写死依赖了collection:1.8.1,other_package中写死依赖了collection:1.9.0,那么我们可以通过如下方法指定一个版本强制覆盖这两个包中声明的版本
dependencies:
some_package:
another_package:
dependency_overrides:
collection: '1.8.2'
若造成冲突的是android平台的包,比如some_package依赖了guava21.0,而other_package依赖了guava22.0,那么可以在android/app/build.gradle文件中配置如下内容强制覆盖guava的版本
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:23.0-android'
}
}
对于iOS的CocoaPods目前还未提供强制覆盖依赖包版本的配置方法
Suppose you want to use some_package
and another_package
in an app, and both of these depend on url_launcher
, but in different versions. That causes a potential conflict. The best way to avoid this is for package authors to use version ranges rather than specific versions when specifying dependencies.
content_copy
dependencies:
url_launcher: ^0.4.2 # Good, any 0.4.x version where x >= 2 works.
image_picker: '0.1.1' # Not so good, only version 0.1.1 works.
If some_package
declares the dependencies above and another_package
declares a compatible url_launcher
dependency like '0.4.5'
or ^0.4.0
, Pub resolves the issue automatically. Platform-specific dependencies on Gradle modules and/or CocoaPods are solved in a similar way.
Even if some_package
and another_package
declare incompatible versions for url_launcher
, they might actually use url_launcher
in compatible ways. In this situation, the conflict can be resolved by adding a dependency override declaration to the app’s pubspec.yaml
file, forcing the use of a particular version.
To force the use of url_launcher
version 0.4.3
, make the following changes to the app’s pubspec.yaml
file:
content_copy
dependencies:
some_package:
another_package:
dependency_overrides:
url_launcher: '0.4.3'
If the conflicting dependency is not itself a package, but an Android-specific library like guava
, the dependency override declaration must be added to Gradle build logic instead.
To force the use of guava
version 23.0
, make the following changes to the app’s android/build.gradle
file:
content_copy
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:23.0-android'
}
}
CocoaPods does not currently offer dependency override functionality.