我已将mlkit添加到flutter项目中,并且在构建时抛出异常。 dart文件和pubspec.yaml文件似乎没有任何错误。
我尝试更改build.gradle文件中的某些内容,但是该操作不起作用,因此我将它们恢复为原始状态
dart代码如下:
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:firebase_ml_vision/firebase_ml_vision.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mlkit/mlkit.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Facial Recognition'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _imageFile;
List<Face> _faces;
List<VisionLabel> _currentLabels = <VisionLabel>[];
bool isLoading = false;
ui.Image _image;
_getImageAndDetectFacesAndObjects() async {
final imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
isLoading = true;
});
final image = FirebaseVisionImage.fromFile(imageFile);
FirebaseVisionLabelDetector detector = FirebaseVisionLabelDetector.instance;
final faceDetector = FirebaseVision.instance.faceDetector();
List<Face> faces = await faceDetector.processImage(image);
List<VisionLabel> currentLabels =
await detector.detectFromBinary(imageFile?.readAsBytesSync());
if (mounted) {
setState(() {
_imageFile = imageFile;
_faces = faces;
_currentLabels = currentLabels;
_loadImage(imageFile);
});
}
}
_loadImage(File file) async {
final data = await file.readAsBytes();
await decodeImageFromList(data).then(
(value) => setState(() {
_image = value;
isLoading = false;
}),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: isLoading
? Center(child: CircularProgressIndicator())
: (_imageFile == null)
? Center(child: Text('No image selected'))
: Center(
child: FittedBox(
child: new Column(
children: <Widget>[
SizedBox(
width: _image.width.toDouble(),
height: _image.height.toDouble(),
child: CustomPaint(
painter: FacePainter(_image, _faces),
),
),
_buildList(_currentLabels)
],
)),
),
floatingActionButton: FloatingActionButton(
onPressed: _getImageAndDetectFacesAndObjects,
tooltip: 'Take Picture',
child: Icon(Icons.add_a_photo),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget _buildList(List<VisionLabel> labels) {
if (labels == null || labels.length == 0) {
return new Text('Empty Image', textAlign: TextAlign.center);
} else {
return new Expanded(
child: new Container(
child: new ListView.builder(
padding: const EdgeInsets.all(1.0),
itemCount: labels.length,
itemBuilder: (context, i) {
return _buildRow(
labels[i].label, labels[i].confidence.toString());
}),
));
}
}
Widget _buildRow(String label, String confidence) {
return new ListTile(
title: new Text(
"\nLabel: $label \nConfidence: $confidence \n",
),
dense: true,
);
}
}
class FacePainter extends CustomPainter {
final ui.Image image;
final List<Face> faces;
final List<Rect> rects = [];
FacePainter(this.image, this.faces) {
for (var i = 0; i < faces.length; i++) {
rects.add(faces[i].boundingBox);
}
}
@override
void paint(ui.Canvas canvas, ui.Size size) {
final Paint paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 15.0
..color = Colors.amber;
canvas.drawImage(image, Offset.zero, Paint());
for (var i = 0; i < faces.length; i++) {
canvas.drawRect(rects[i], paint);
}
}
@override
bool shouldRepaint(FacePainter oldDelegate) {
return image != oldDelegate.image || faces != oldDelegate.faces;
}
}
应用程序级别的build.gradle文件如下所示:
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 28
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.facial_app"
minSdkVersion 16
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
api 'com.google.firebase:firebase-ml-vision-face-model:18.0.0'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-ml-vision:23.0.0'
// If you want to detect face contours (landmark detection and classification
// don't require this additional model):
implementation 'com.google.firebase:firebase-ml-vision-face-model:18.0.0'
}
apply plugin: 'com.google.gms.google-services'
项目级别的build.gradle如下所示:
buildscript {
ext.kotlin_version = '1.2.71'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:3.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
subprojects {
project.configurations.all {
resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'androidx.core'
&& !details.requested.name.contains('androidx') ) {
details.useVersion "1.0.1"
}
}
}
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
抛出的错误是这样的:
D8: Type com.google.android.gms.internal.firebase_ml.zzop is referenced as an interface from `com.google.android.gms.internal.firebase_ml.zzpu`.
D8: Type com.google.android.gms.internal.firebase_ml.zzny is referenced as an interface from `com.google.android.gms.internal.firebase_ml.zzpy`.
D8: Type com.google.android.gms.internal.firebase_ml.zzny is referenced as an interface from `com.google.android.gms.internal.firebase_ml.zzpv`.
com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\user\.gradle\caches\transforms-1\files-1.1\jetified-firebase-ml-model-interpreter-19.0.0.aar\b00f4f536c45683495ade7150f92c485\jars\classes.jar
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:720)
at com.android.ide.common.internal.WaitableExecutor.waitForTasksWithQuickFail(WaitableExecutor.java:146)
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.transform(DexArchiveBuilderTransform.java:405)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
at sun.reflect.GeneratedMethodAccessor660.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\user\.gradle\caches\transforms-1\files-1.1\jetified-firebase-ml-model-interpreter-19.0.0.aar\b00f4f536c45683495ade7150f92c485\jars\classes.jar
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:900)
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.lambda$convertToDexArchive$6(DexArchiveBuilderTransform.java:825)
at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.
at com.android.builder.dexing.D8DexArchiveBuilder.getExceptionToRethrow(D8DexArchiveBuilder.java:124)
at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:101)
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:895)
... 6 more
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:65)
at com.android.tools.r8.utils.ExceptionUtils.withD8CompilationHandler(ExceptionUtils.java:43)
at com.android.tools.r8.D8.run(D8.java:90)
at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:99)
... 7 more
Caused by: com.android.tools.r8.utils.AbortException: Error: Type com.google.android.gms.internal.firebase_ml.zzny is referenced as an interface from `com.google.android.gms.internal.firebase_ml.zzpv`.
at com.android.tools.r8.utils.Reporter.failIfPendingErrors(Reporter.java:116)
at com.android.tools.r8.utils.Reporter.fatalError(Reporter.java:74)
at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:59)
... 10 more
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\user\.gradle\caches\transforms-1\files-1.1\jetified-firebase-ml-model-interpreter-19.0.0.aar\b00f4f536c45683495ade7150f92c485\jars\classes.jar
答案 0 :(得分:0)
我只是用此代码修复了它。
local.properties
org.gradle.jvmargs=-XX\:MaxHeapSize\=512m -Xmx512m
,您应该在应用程序级别build.gradle上添加它
defaultConfig {
applicationId "yourProjectPackage"
minSdkVersion 16
versionCode 1
versionName "1.0"
targetSdkVersion 28
multiDexEnabled true //important
}